python类iterable()的实例源码

stride_tricks.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def _broadcast_to(array, shape, subok, readonly):
    shape = tuple(shape) if np.iterable(shape) else (shape,)
    array = np.array(array, copy=False, subok=subok)
    if not shape and array.shape:
        raise ValueError('cannot broadcast a non-scalar to a scalar array')
    if any(size < 0 for size in shape):
        raise ValueError('all elements of broadcast shape must be non-'
                         'negative')
    needs_writeable = not readonly and array.flags.writeable
    extras = ['reduce_ok'] if needs_writeable else []
    op_flag = 'readwrite' if needs_writeable else 'readonly'
    broadcast = np.nditer(
        (array,), flags=['multi_index', 'refs_ok', 'zerosize_ok'] + extras,
        op_flags=[op_flag], itershape=shape, order='C').itviews[0]
    result = _maybe_view_as_subclass(array, broadcast)
    if needs_writeable and not result.flags.writeable:
        result.flags.writeable = True
    return result
attributes.py 文件源码 项目:pyrpl 作者: lneuhaus 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def valid_frequencies(self, obj):
        """ returns a list of all valid filter cutoff frequencies"""
        #valid_bits = range(0, self._MAXSHIFT(obj)-1)  # this is possible
        valid_bits = range(0, self._MAXSHIFT(obj)-2)  # this gives reasonable results (test_filter)
        pos = list([self.to_python(obj, b | 0x1 << 7) for b in valid_bits])
        pos = [val if not np.iterable(val) else val[0] for val in pos]
        neg = [-val for val in reversed(pos)]
        valid_frequencies = neg + [0] + pos
        if obj is not None and not hasattr(obj.__class__,
                                           self.name+'_options') and not hasattr(obj, self.name+'_options'):
            setattr(obj, self.name+'_options', valid_frequencies)
        return valid_frequencies

    # empirical correction factors for the cutoff frequencies in order to be
    # able to accurately model implemented bandwidth with an analog
    # butterworth filter. Works well up to 5 MHz. See unittest test_inputfilter
binnings.py 文件源码 项目:physt 作者: janpipek 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def force_bin_existence(self, values):
        """Change schema so that there is a bin for value.

        It is necessary to implement the _force_bin_existence template method.

        Parameters
        ----------
        values: np.ndarray
            All values we want bins for.

        Returns
        -------
        bin_map: Iterable[tuple] or None or int
            None => There was no change in bins
            int => The bins are only shifted (allows mass assignment)
            Otherwise => the iterable contains tuples (old bin index, new bin index)
                new bin index can occur multiple times, which corresponds to bin merging
        """
        # TODO: Rename to something less evil
        if not self.is_adaptive():
            raise RuntimeError("Histogram is not adaptive")
        else:
            return self._force_bin_existence(values)
stride_tricks.py 文件源码 项目:krpcScripts 作者: jwvanderbeck 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def _broadcast_to(array, shape, subok, readonly):
    shape = tuple(shape) if np.iterable(shape) else (shape,)
    array = np.array(array, copy=False, subok=subok)
    if not shape and array.shape:
        raise ValueError('cannot broadcast a non-scalar to a scalar array')
    if any(size < 0 for size in shape):
        raise ValueError('all elements of broadcast shape must be non-'
                         'negative')
    needs_writeable = not readonly and array.flags.writeable
    extras = ['reduce_ok'] if needs_writeable else []
    op_flag = 'readwrite' if needs_writeable else 'readonly'
    broadcast = np.nditer(
        (array,), flags=['multi_index', 'refs_ok', 'zerosize_ok'] + extras,
        op_flags=[op_flag], itershape=shape, order='C').itviews[0]
    result = _maybe_view_as_subclass(array, broadcast)
    if needs_writeable and not result.flags.writeable:
        result.flags.writeable = True
    return result
cmq_cashflow.py 文件源码 项目:pyktrader2 作者: harveywwu 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def value(self, proj, disc, spread=0.0):
            """
            the coupons of the leg must be unpaid yet as of today (assuming today is the valuation date):                    
            |-----|-----------------------|---|
            F0   A0s                     A0e  P0  
                                    |-----|-----------------------|---|
                                    F1   A1s                     A1e  P1   
                                                            |-----|-----------------------|---|
                                                            F2   A2s                     A2e  P2         
            It can be that F1 < today < P0, there would be 2 unpaid but fixed coupons, however this is very rare.
            """
            if isinstance(proj, (float, int)): # proj is a single float, e.g. a single fixed rate
                rates = proj             
            elif np.iterable(proj): # proj is a vector of floats, e.g. predefined fixed rates           
                assert len(proj) == len(self.cp)
                rates = proj                      
            elif callable(proj): # proj is a curve or a function, a floating leg
                rates = np.array([p.index.forward(proj) for p in self.cp])
            else: 
                raise BaseException('invalid rate/projection ...') 

            rates = rates * self.factory.rate_leverage + self.factory.rate_spread
            return self.np_effnotl.dot((rates + spread) * disc(self.np_paydates))
stride_tricks.py 文件源码 项目:aws-lambda-numpy 作者: vitolimandibhrata 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def _broadcast_to(array, shape, subok, readonly):
    shape = tuple(shape) if np.iterable(shape) else (shape,)
    array = np.array(array, copy=False, subok=subok)
    if not shape and array.shape:
        raise ValueError('cannot broadcast a non-scalar to a scalar array')
    if any(size < 0 for size in shape):
        raise ValueError('all elements of broadcast shape must be non-'
                         'negative')
    needs_writeable = not readonly and array.flags.writeable
    extras = ['reduce_ok'] if needs_writeable else []
    op_flag = 'readwrite' if needs_writeable else 'readonly'
    broadcast = np.nditer(
        (array,), flags=['multi_index', 'refs_ok', 'zerosize_ok'] + extras,
        op_flags=[op_flag], itershape=shape, order='C').itviews[0]
    result = _maybe_view_as_subclass(array, broadcast)
    if needs_writeable and not result.flags.writeable:
        result.flags.writeable = True
    return result
stride_tricks.py 文件源码 项目:lambda-numba 作者: rlhotovy 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
def _broadcast_to(array, shape, subok, readonly):
    shape = tuple(shape) if np.iterable(shape) else (shape,)
    array = np.array(array, copy=False, subok=subok)
    if not shape and array.shape:
        raise ValueError('cannot broadcast a non-scalar to a scalar array')
    if any(size < 0 for size in shape):
        raise ValueError('all elements of broadcast shape must be non-'
                         'negative')
    needs_writeable = not readonly and array.flags.writeable
    extras = ['reduce_ok'] if needs_writeable else []
    op_flag = 'readwrite' if needs_writeable else 'readonly'
    broadcast = np.nditer(
        (array,), flags=['multi_index', 'refs_ok', 'zerosize_ok'] + extras,
        op_flags=[op_flag], itershape=shape, order='C').itviews[0]
    result = _maybe_view_as_subclass(array, broadcast)
    if needs_writeable and not result.flags.writeable:
        result.flags.writeable = True
    return result
core.py 文件源码 项目:soif 作者: ceyzeriat 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def round_fig(x, n=1, retint=False):
    """
    Rounds x at the n-th figure. n must be >1
    ex: 1234.567 with n=3-> 1230.0
    """
    if np.iterable(x):
        x = np.asarray(x).copy()
        ff = (x != 0)
        dd = 10**(np.floor(np.log10(np.abs(x[ff])))-n+1)
        x[ff] = np.round(x[ff]/dd)
        if not retint:
            x[ff] *= dd
        return x
    elif x != 0:
        dd = 10**(np.floor(np.log10(np.abs(x)))-n+1)
        x = np.round(x/dd)
        if not retint:
            x *= dd
        return x
    else:
        return x
template_store.py 文件源码 项目:spyking-circus-ort 作者: spyking-circus 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def remove(self, indices):

        if not np.iterable(indices):
            indices = [indices]

        self._open('r+')

        for index in indices:
            assert index in indices
            self.h5_file.pop('waveforms/%d' % index)
            self.h5_file.pop('amplitudes/%d' % index)
            channels = self.h5_file.pop('channels')
            times = self.h5_file.pop('times')
            indices = self.h5_file.pop('indices')
            to_remove = np.where(indices == index)[0]
            self.h5_file['channels'] = np.delete(channels, to_remove)
            self.h5_file['indices'] = np.delete(indices, to_remove)
            self.h5_file['times'] = np.delete(times, to_remove)

        self._close()

        return
synthetic.py 文件源码 项目:spyking-circus-ort 作者: spyking-circus 项目源码 文件源码 阅读 38 收藏 0 点赞 0 评论 0
def get(self, indices=None, variables=None):

        result = {}

        self.h5_file = h5py.File(self.file_name, 'r')

        if indices is None:
            indices = self.h5_file.keys()
        elif not numpy.iterable(indices):
            indices = [indices]

        if variables is None:
            variables = self.variables
        elif not isinstance(variables, list):
            variables = [variables]

        for cell_id in indices:
            result[cell_id] = {}
            for key in variables:
                result[cell_id][key] = self.h5_file['{c}/{d}'.format(c=cell_id, d=key)][:]

        self.h5_file.close()

        return result
stride_tricks.py 文件源码 项目:deliver 作者: orchestor 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def _broadcast_to(array, shape, subok, readonly):
    shape = tuple(shape) if np.iterable(shape) else (shape,)
    array = np.array(array, copy=False, subok=subok)
    if not shape and array.shape:
        raise ValueError('cannot broadcast a non-scalar to a scalar array')
    if any(size < 0 for size in shape):
        raise ValueError('all elements of broadcast shape must be non-'
                         'negative')
    needs_writeable = not readonly and array.flags.writeable
    extras = ['reduce_ok'] if needs_writeable else []
    op_flag = 'readwrite' if needs_writeable else 'readonly'
    broadcast = np.nditer(
        (array,), flags=['multi_index', 'refs_ok', 'zerosize_ok'] + extras,
        op_flags=[op_flag], itershape=shape, order='C').itviews[0]
    result = _maybe_view_as_subclass(array, broadcast)
    if needs_writeable and not result.flags.writeable:
        result.flags.writeable = True
    return result
Vector.py 文件源码 项目:PyValentina 作者: FabriceSalvaire 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def __init__(self, *args):

        """
        Example of usage::

          Vector(1, 3)
          Vector((1, 3))
          Vector([1, 3])
          Vector(iterable)
          Vector(vector)

        """

        array = self._check_arguments(args)

        # call __getitem__ once
        self._v = np.array(array[:2], dtype=self.__data_type__)

    ##############################################
Vector.py 文件源码 项目:PyValentina 作者: FabriceSalvaire 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def _check_arguments(self, args):

        size = len(args)
        if size == 1:
            array = args[0]
        elif size == 2:
            array = args
        else:
            raise ValueError("More than 2 arguments where given")

        if not (np.iterable(array) and len(array) == 2):
            raise ValueError("Argument must be iterable and of length 2")

        return array

    ##############################################
kernels.py 文件源码 项目:Parallel-SGD 作者: angadgill 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def __init__(self, length_scale=1.0, length_scale_bounds=(1e-5, 1e5)):
        if np.iterable(length_scale):
            if len(length_scale) > 1:
                self.anisotropic = True
                self.length_scale = np.asarray(length_scale, dtype=np.float)
            else:
                self.anisotropic = False
                self.length_scale = float(length_scale[0])
        else:
            self.anisotropic = False
            self.length_scale = float(length_scale)
        self.length_scale_bounds = length_scale_bounds

        if self.anisotropic:  # anisotropic length_scale
            self.hyperparameter_length_scale = \
                Hyperparameter("length_scale", "numeric", length_scale_bounds,
                               len(length_scale))
        else:
            self.hyperparameter_length_scale = \
                Hyperparameter("length_scale", "numeric", length_scale_bounds)
stride_tricks.py 文件源码 项目:Alfred 作者: jkachhadia 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def _broadcast_to(array, shape, subok, readonly):
    shape = tuple(shape) if np.iterable(shape) else (shape,)
    array = np.array(array, copy=False, subok=subok)
    if not shape and array.shape:
        raise ValueError('cannot broadcast a non-scalar to a scalar array')
    if any(size < 0 for size in shape):
        raise ValueError('all elements of broadcast shape must be non-'
                         'negative')
    needs_writeable = not readonly and array.flags.writeable
    extras = ['reduce_ok'] if needs_writeable else []
    op_flag = 'readwrite' if needs_writeable else 'readonly'
    broadcast = np.nditer(
        (array,), flags=['multi_index', 'refs_ok', 'zerosize_ok'] + extras,
        op_flags=[op_flag], itershape=shape, order='C').itviews[0]
    result = _maybe_view_as_subclass(array, broadcast)
    if needs_writeable and not result.flags.writeable:
        result.flags.writeable = True
    return result
plot.py 文件源码 项目:spyking-circus 作者: spyking-circus 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def view_raw_templates(file_name, n_temp=2, square=True):

    N_e, N_t, N_tm = templates.shape
    if not numpy.iterable(n_temp):
        if square:
            idx = numpy.random.permutation(numpy.arange(N_tm//2))[:n_temp**2]
        else:
            idx = numpy.random.permutation(numpy.arange(N_tm//2))[:n_temp]
    else:
        idx = n_temp

    import matplotlib.colors as colors
    my_cmap   = pylab.get_cmap('winter')
    cNorm     = colors.Normalize(vmin=0, vmax=N_e)
    scalarMap = pylab.cm.ScalarMappable(norm=cNorm, cmap=my_cmap)

    pylab.figure()
    for count, i in enumerate(idx):
        if square:
            pylab.subplot(n_temp, n_temp, count + 1)
            if (numpy.mod(count, n_temp) != 0):
                pylab.setp(pylab.gca(), yticks=[])
            if (count < n_temp*(n_temp - 1)):
                pylab.setp(pylab.gca(), xticks=[])
        else:
            pylab.subplot(len(idx), 1, count + 1)
            if count != (len(idx) - 1):
                pylab.setp(pylab.gca(), xticks=[])
        for j in xrange(N_e):
            colorVal = scalarMap.to_rgba(j)
            pylab.plot(templates[j, :, i], color=colorVal)

        pylab.title('Template %d' %i)
    pylab.tight_layout()
    pylab.show()
function_base.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def iterable(y):
    """
    Check whether or not an object can be iterated over.

    Parameters
    ----------
    y : object
      Input object.

    Returns
    -------
    b : {0, 1}
      Return 1 if the object has an iterator method or is a sequence,
      and 0 otherwise.


    Examples
    --------
    >>> np.iterable([1, 2, 3])
    1
    >>> np.iterable(2)
    0

    """
    try:
        iter(y)
    except:
        return 0
    return 1
function_base.py 文件源码 项目:radar 作者: amoose136 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def __init__(self, pyfunc, otypes='', doc=None, excluded=None,
                 cache=False):
        self.pyfunc = pyfunc
        self.cache = cache
        self._ufunc = None    # Caching to improve default performance

        if doc is None:
            self.__doc__ = pyfunc.__doc__
        else:
            self.__doc__ = doc

        if isinstance(otypes, str):
            self.otypes = otypes
            for char in self.otypes:
                if char not in typecodes['All']:
                    raise ValueError(
                        "Invalid otype specified: %s" % (char,))
        elif iterable(otypes):
            self.otypes = ''.join([_nx.dtype(x).char for x in otypes])
        else:
            raise ValueError(
                "Invalid otype specification")

        # Excluded variable support
        if excluded is None:
            excluded = set()
        self.excluded = set(excluded)
toplevel.py 文件源码 项目:SegmentationService 作者: jingchaoluan 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def checktype(value,type_):
    """Check value against the type spec.  If everything
    is OK, this just returns the value itself.
    If the types don't check out, an exception is thrown."""
    # True skips any check
    if type_ is True:
        return value
    # types are checked using isinstance
    if type(type_)==type:
        if not isinstance(value,type_):
            raise CheckError("isinstance failed",value,"of type",type(value),"is not of type",type_)
        return value
    # for a list, check that all elements of a collection have a type
    # of some list element, allowing declarations like [str] or [str,unicode]
    # no recursive checks right now
    if type(type_)==list:
        if not numpy.iterable(value):
            raise CheckError("expected iterable",value)
        for x in value:
            if not reduce(max,[isinstance(x,t) for t in type_]):
                raise CheckError("element",x,"of type",type(x),"fails to be of type",type_)
        return value
    # for sets, check membership of the type in the set
    if type(type_)==set:
        for t in type_:
            if isinstance(value,t): return value
        raise CheckError("set membership failed",value,type_,var=var) # FIXME var?
    # for tuples, check that all conditions are satisfied
    if type(type_)==tuple:
        for t in type_:
            checktype(value,type_)
        return value
    # callables are just called and should either use assertions or
    # explicitly raise CheckError
    if callable(type_):
        type_(value)
        return value
    # otherwise, we don't understand the type spec
    raise Exception("unknown type spec: %s"%type_)
attributes.py 文件源码 项目:pyrpl 作者: lneuhaus 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def validate_and_normalize(self, obj, value):
        """
        Returns a list with the closest elements in module.valid_frequencies
        """
        if not np.iterable(value):
            value = [value]
        value = [min([opt for opt in self.valid_frequencies(obj)],
                      key=lambda x: abs(x - val)) for val in value]
        if len(value) == 1:
            return value[0]
        else:
            return value
attributes.py 文件源码 项目:pyrpl 作者: lneuhaus 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def extend(self, iterable=[]):
        for i in iterable:
            self.append(i)
attribute_widgets.py 文件源码 项目:pyrpl 作者: lneuhaus 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def set_list(self, val):
        if not np.iterable(val):
            val = [val]
        for i, v in enumerate(val):
            #v = str(int(v))
            v = ('{:.' + str(self.decimals) + 'e}').format(float(v))
            index = self.options.index(v)
            self.combos[i].setCurrentIndex(index)
attribute_widgets.py 文件源码 项目:pyrpl 作者: lneuhaus 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def __init__(self, module, attribute_name, widget_name=None):
        val = getattr(module, attribute_name)
        if np.iterable(val):
            self.number = len(val)
        else:
            self.number = 1
        self.options = getattr(module.__class__, attribute_name).valid_frequencies(module)
        super(FilterAttributeWidget, self).__init__(module, attribute_name,
                                                    widget_name=widget_name)
iq.py 文件源码 项目:pyrpl 作者: lneuhaus 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def set_value(self, instance, val):
        if np.iterable(val):
            val = val[0]
        val = float(val)
        instance.inputfilter = -val
        return val
iir.py 文件源码 项目:pyrpl 作者: lneuhaus 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def validate_and_normalize(self, obj, value):
        """
        Converts the value in a list of float numbers.
        """
        if not np.iterable(value):
            value = [value]
        return [self.validate_and_normalize_element(obj, val) for val in value]
binnings.py 文件源码 项目:physt 作者: janpipek 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def numpy_binning(data, bins=10, range=None, *args, **kwargs):
    """Construct binning schema compatible with numpy.histogram

    Parameters
    ----------
    data: array_like, optional
        This is optional if both bins and range are set
    bins: int or array_like
    range: Optional[tuple]
        (min, max)
    includes_right_edge: Optional[bool]
        default: True

    Returns
    -------
    NumpyBinning

    See Also
    --------
    numpy.histogram
    """
    if isinstance(bins, int):
        if range:
            bins = np.linspace(range[0], range[1], bins + 1)
        else:
            start = data.min()
            stop = data.max()
            bins = np.linspace(start, stop, bins + 1)
    elif np.iterable(bins):
        bins = np.asarray(bins)
    else:
        # Some numpy edge case
        _, bins = np.histogram(data, bins, **kwargs)
    return NumpyBinning(bins)
function_base.py 文件源码 项目:krpcScripts 作者: jwvanderbeck 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def iterable(y):
    """
    Check whether or not an object can be iterated over.

    Parameters
    ----------
    y : object
      Input object.

    Returns
    -------
    b : {0, 1}
      Return 1 if the object has an iterator method or is a sequence,
      and 0 otherwise.


    Examples
    --------
    >>> np.iterable([1, 2, 3])
    1
    >>> np.iterable(2)
    0

    """
    try:
        iter(y)
    except:
        return 0
    return 1
function_base.py 文件源码 项目:krpcScripts 作者: jwvanderbeck 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def __init__(self, pyfunc, otypes='', doc=None, excluded=None,
                 cache=False):
        self.pyfunc = pyfunc
        self.cache = cache
        self._ufunc = None    # Caching to improve default performance

        if doc is None:
            self.__doc__ = pyfunc.__doc__
        else:
            self.__doc__ = doc

        if isinstance(otypes, str):
            self.otypes = otypes
            for char in self.otypes:
                if char not in typecodes['All']:
                    raise ValueError(
                        "Invalid otype specified: %s" % (char,))
        elif iterable(otypes):
            self.otypes = ''.join([_nx.dtype(x).char for x in otypes])
        else:
            raise ValueError(
                "Invalid otype specification")

        # Excluded variable support
        if excluded is None:
            excluded = set()
        self.excluded = set(excluded)
sersic.py 文件源码 项目:CAAPR 作者: Stargrazer82301 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def bm_bn_estimate(nn):
    "Guess for bn constant defined by B+M"
    if np.iterable(nn): return np.array([bm_bn_estimate(n) for n in nn])
    est = 0.87*nn-0.15
    if nn < 0.2: est = 0.01*(nn/0.1)**4
    return est
sersic.py 文件源码 项目:CAAPR 作者: Stargrazer82301 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def bg_3d_lum_int_func(pp,qq):
    """Return a function that gives deprojected sersic profile"""
    i0,bb = bg_constants(pp, qq)
    def ff(xx):
        if np.iterable(xx):
            return [ff(x) for x in xx]
        return float(bg_3d_lum_int(xx,pp,qq,i0,bb))
    return ff


问题


面经


文章

微信
公众号

扫码关注公众号