Python numpy 模块,iterable() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用numpy.iterable()

项目:radar    作者:amoose136    | 项目源码 | 文件源码
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
项目:pyrpl    作者:lneuhaus    | 项目源码 | 文件源码
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
项目:physt    作者:janpipek    | 项目源码 | 文件源码
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)
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
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
项目:pyktrader2    作者:harveywwu    | 项目源码 | 文件源码
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))
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
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
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
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
项目:soif    作者:ceyzeriat    | 项目源码 | 文件源码
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
项目:spyking-circus-ort    作者:spyking-circus    | 项目源码 | 文件源码
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
项目:spyking-circus-ort    作者:spyking-circus    | 项目源码 | 文件源码
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
项目:deliver    作者:orchestor    | 项目源码 | 文件源码
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
项目:PyValentina    作者:FabriceSalvaire    | 项目源码 | 文件源码
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__)

    ##############################################
项目:PyValentina    作者:FabriceSalvaire    | 项目源码 | 文件源码
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

    ##############################################
项目:Parallel-SGD    作者:angadgill    | 项目源码 | 文件源码
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)
项目:Alfred    作者:jkachhadia    | 项目源码 | 文件源码
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
项目:spyking-circus    作者:spyking-circus    | 项目源码 | 文件源码
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()
项目:radar    作者:amoose136    | 项目源码 | 文件源码
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
项目:radar    作者:amoose136    | 项目源码 | 文件源码
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)
项目:SegmentationService    作者:jingchaoluan    | 项目源码 | 文件源码
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_)
项目:pyrpl    作者:lneuhaus    | 项目源码 | 文件源码
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
项目:pyrpl    作者:lneuhaus    | 项目源码 | 文件源码
def extend(self, iterable=[]):
        for i in iterable:
            self.append(i)
项目:pyrpl    作者:lneuhaus    | 项目源码 | 文件源码
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)
项目:pyrpl    作者:lneuhaus    | 项目源码 | 文件源码
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)
项目:pyrpl    作者:lneuhaus    | 项目源码 | 文件源码
def set_value(self, instance, val):
        if np.iterable(val):
            val = val[0]
        val = float(val)
        instance.inputfilter = -val
        return val
项目:pyrpl    作者:lneuhaus    | 项目源码 | 文件源码
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]
项目:physt    作者:janpipek    | 项目源码 | 文件源码
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)
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
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
项目:krpcScripts    作者:jwvanderbeck    | 项目源码 | 文件源码
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)
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
def bg_lum_hi(pp, qq):
    # Tested 2011-08-31
    """Exact deprojection of Sersic profile using Meijer G function as
    described by Baes + Gentile 1009.4713.  Use formula valid for half
    integers"""

    if not (pp==int(pp) and qq==int(qq)): raise RuntimeError
    if not (qq == 1 or qq == 2): raise RuntimeError

    pp, qq = int(pp), int(qq)    
    mm = (1.0*pp)/qq
    i0, bb = bg_constants(pp, qq)

    # a and b vectors are specified: [[num1, num2, num3],[denom1,denom2,denom3]]    
    avect = [[], []]
    nums = range(1,2*pp/qq)
    bvect = [[xx/(2.0*mm) for xx in nums] + [0.5], []]
    reff = 1.0

    factor = 2*i0*np.sqrt(mm)/(reff*(2*np.pi)**mm)

    def lum(rr):
        if np.iterable(rr): return np.array([lum(r) for r in rr])
        ss = rr/reff
        zz = (bb/(2*mm))**(2*mm) * ss**2
        return (factor/ss)*mpmath.meijerg(avect, bvect, zz)

    return lum

##################################################
## The big money function is defined right here!  The name conforms to
## naming conventions used throughout this file, but is nearly useless
## to users.  So make it available as luminosity() to users via a line
## in __init__.py since it's likely the only function any user will
## care about.
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
def bg_lum(pp, qq, reff=1.0, lum=1.0):
    # Tested 2011-08-31
    """Exact deprojection of Sersic profile using Meijer G function as
    described by Baes + Gentile arxiv:1009.4713.

    pp and qq are the numerator and denominator of the Sersic index
      (both integers) so that n=pp/qq, 
    reff is the projected half-light radius
    lum is the total luminosity.  

    This returns a function that takes a radius and returns a
    luminosity density.

    >>> lum = luminosity(5,3)
    >>> lum(1.1)
    >>> lum([1.1, 2.2, 3.3])

    """
    if not (pp==int(pp) and qq==int(qq)): raise RuntimeError
    pp, qq = int(pp), int(qq)
    i0, bb = bg_constants(pp, qq)

    # Solution gets slow for larger p,q, so make sure that fraction is reduced
    the_gcf = euclid_gcf(pp,qq)    
    if the_gcf != 1: return bg_lum(pp/the_gcf, qq/the_gcf)        

    # a and b vectors are specified: [[num1, num2, num3],[denom1,denom2,denom3]]    
    avect = [[], [xx/(1.0*qq) for xx in range(1,qq)]]
    bvect = [[xx/(2.0*pp) for xx in range(1,2*pp)] +
             [xx/(2.0*qq) for xx in range(1,2*qq,2)], []]
    factor = 2*i0*np.sqrt(pp*qq)/(reff*(2*np.pi)**pp)

    def luminosity(rr):
        if np.iterable(rr): return np.array([luminosity(r) for r in rr])
        ss = rr/reff
        zz = (bb/(2*pp))**(2*pp) * ss**(2*qq)
        return lum*((factor/ss)*mpmath.meijerg(avect, bvect, zz))

    return luminosity
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
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
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
def bg_lum_hi(pp, qq):
    # Tested 2011-08-31
    """Exact deprojection of Sersic profile using Meijer G function as
    described by Baes + Gentile 1009.4713.  Use formula valid for half
    integers"""

    if not (pp==int(pp) and qq==int(qq)): raise RuntimeError
    if not (qq == 1 or qq == 2): raise RuntimeError

    pp, qq = int(pp), int(qq)    
    mm = (1.0*pp)/qq
    i0, bb = bg_constants(pp, qq)

    # a and b vectors are specified: [[num1, num2, num3],[denom1,denom2,denom3]]    
    avect = [[], []]
    nums = range(1,2*pp/qq)
    bvect = [[xx/(2.0*mm) for xx in nums] + [0.5], []]
    reff = 1.0

    factor = 2*i0*np.sqrt(mm)/(reff*(2*np.pi)**mm)

    def lum(rr):
        if np.iterable(rr): return np.array([lum(r) for r in rr])
        ss = rr/reff
        zz = (bb/(2*mm))**(2*mm) * ss**2
        return (factor/ss)*mpmath.meijerg(avect, bvect, zz)

    return lum

##################################################
## The big money function is defined right here!  The name conforms to
## naming conventions used throughout this file, but is nearly useless
## to users.  So make it available as luminosity() to users via a line
## in __init__.py since it's likely the only function any user will
## care about.
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
def bg_lum(pp, qq, reff=1.0, lum=1.0):
    # Tested 2011-08-31
    """Exact deprojection of Sersic profile using Meijer G function as
    described by Baes + Gentile arxiv:1009.4713.

    pp and qq are the numerator and denominator of the Sersic index
      (both integers) so that n=pp/qq, 
    reff is the projected half-light radius
    lum is the total luminosity.  

    This returns a function that takes a radius and returns a
    luminosity density.

    >>> lum = luminosity(5,3)
    >>> lum(1.1)
    >>> lum([1.1, 2.2, 3.3])

    """
    if not (pp==int(pp) and qq==int(qq)): raise RuntimeError
    pp, qq = int(pp), int(qq)
    i0, bb = bg_constants(pp, qq)

    # Solution gets slow for larger p,q, so make sure that fraction is reduced
    the_gcf = euclid_gcf(pp,qq)    
    if the_gcf != 1: return bg_lum(pp/the_gcf, qq/the_gcf)        

    # a and b vectors are specified: [[num1, num2, num3],[denom1,denom2,denom3]]    
    avect = [[], [xx/(1.0*qq) for xx in range(1,qq)]]
    bvect = [[xx/(2.0*pp) for xx in range(1,2*pp)] +
             [xx/(2.0*qq) for xx in range(1,2*qq,2)], []]
    factor = 2*i0*np.sqrt(pp*qq)/(reff*(2*np.pi)**pp)

    def luminosity(rr):
        if np.iterable(rr): return np.array([luminosity(r) for r in rr])
        ss = rr/reff
        zz = (bb/(2*pp))**(2*pp) * ss**(2*qq)
        return lum*((factor/ss)*mpmath.meijerg(avect, bvect, zz))

    return luminosity
项目:tncontract    作者:andrewdarmawan    | 项目源码 | 文件源码
def init_mps_random(nsites, physdim, bonddim=1, left_label='left',
                    right_label='right', phys_label='phys'):
    """
    Create an MPS with `nsites` sites and random tensors with physical 
    dimensions given by `physdim` and bond dimensions given by
    `bonddim`. Open boundary conditions are used. The MPS is not normalized.

    Parameters
    ----------
    nsites : int
    physdim : int or list of ints
    bonddim : int or list of ints, optional
        The nth element of `bonddim` determines the right and left index of
        the tensors at sites n and n+1, respectively. The length of `bonddim`
        should be `nsites`-1. If `bonddim` is an int this is this is used for
        all bonds.
    left_label : str
    right_label : str
    phys_label : str
    """
    if not np.iterable(physdim):
        physdim = [physdim] * nsites
    if not np.iterable(bonddim):
        bonddim = [bonddim] * (nsites - 1)
    bonddim = [1] + bonddim + [1]
    tensors = []
    for i in range(nsites):
        rt = tnc.Tensor(np.random.rand(
            physdim[i], bonddim[i], bonddim[i + 1]),
            [phys_label, left_label, right_label])
        # Normalize matrix to avoid norm blowing up
        U, S, V = tnc.tensor_svd(rt, [phys_label, left_label])
        S.data = S.data / S.data[0, 0]
        rt = U["svd_in",] * S["svd_out",]
        rt = rt["svd_in",] * V["svd_out",]
        tensors.append(rt)
    return onedim.MatrixProductState(tensors, left_label=left_label,
                                     right_label=right_label, phys_label=phys_label)
项目:tncontract    作者:andrewdarmawan    | 项目源码 | 文件源码
def init_mps_allzero(nsites, physdim, left_label='left',
                     right_label='right', phys_label='phys'):
    """
    Create an MPS with `nsites` sites in the "all zero" state |00..0>.

    Parameters
    ----------
    nsites : int
    physdim : int or list of ints
    left_label : str
    right_label : str
    phys_label : str
    """
    if not np.iterable(physdim):
        physdim = [physdim] * nsites

    tensors = []
    for j in range(nsites):
        t = np.zeros(physdim[j])
        t[0] = 1.0
        t = tnc.Tensor(t.reshape(physdim[j], 1, 1), [phys_label, left_label,
                                                     right_label])
        tensors.append(t)

    return onedim.MatrixProductState(tensors, left_label=left_label,
                                     right_label=right_label, phys_label=phys_label)
项目:tncontract    作者:andrewdarmawan    | 项目源码 | 文件源码
def init_mps_logical(nsites, basis_state, physdim, left_label='left',
                     right_label='right', phys_label='phys'):
    """
    Create an MPS with `nsites` sites in the logical basis state |ijk..l>.

    Parameters
    ----------
    nsites : int
    basis_state : int or list of ints
        Site `i` will be in the state |`basis_state[i]`> (or simply
        |`basis_state`> if a single int is provided).
    physdim : int or list of ints
    left_label : str
    right_label : str
    phys_label : str
    """
    if not np.iterable(physdim):
        physdim = [physdim] * nsites

    tensors = []
    for j in range(nsites):
        t = np.zeros(physdim[j])
        t[basis_state[j]] = 1.0
        t = tnc.Tensor(t.reshape(physdim[j], 1, 1), [phys_label, left_label,
                                                     right_label])
        tensors.append(t)

    return onedim.MatrixProductState(tensors, left_label=left_label,
                                     right_label=right_label, phys_label=phys_label)
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def __iter__(self):
        raise NotImplementedError('ix is not iterable')
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def _should_validate_iterable(self, axis=0):
        """ return a boolean whether this axes needs validation for a passed
        iterable
        """
        ax = self.obj._get_axis(axis)
        if isinstance(ax, MultiIndex):
            return False
        elif ax.is_floating():
            return False

        return True
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda    作者:SignalMedia    | 项目源码 | 文件源码
def _getitem_axis(self, key, axis=0):
        labels = self.obj._get_axis(axis)

        if isinstance(key, slice):
            self._has_valid_type(key, axis)
            return self._get_slice_axis(key, axis=axis)
        elif is_bool_indexer(key):
            return self._getbool_axis(key, axis=axis)
        elif is_list_like_indexer(key):

            # GH 7349
            # possibly convert a list-like into a nested tuple
            # but don't convert a list-like of tuples
            if isinstance(labels, MultiIndex):
                if (not isinstance(key, tuple) and len(key) > 1 and
                        not isinstance(key[0], tuple)):
                    key = tuple([key])

            # an iterable multi-selection
            if not (isinstance(key, tuple) and isinstance(labels, MultiIndex)):

                if hasattr(key, 'ndim') and key.ndim > 1:
                    raise ValueError('Cannot index with multidimensional key')

                return self._getitem_iterable(key, axis=axis)

            # nested tuple slicing
            if is_nested_tuple(key, labels):
                locs = labels.get_locs(key)
                indexer = [slice(None)] * self.ndim
                indexer[axis] = locs
                return self.obj.iloc[tuple(indexer)]

        # fall thru to straight lookup
        self._has_valid_type(key, axis)
        return self._get_label(key, axis=axis)
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
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
项目:aws-lambda-numpy    作者:vitolimandibhrata    | 项目源码 | 文件源码
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)
项目:mcplates    作者:ian-r-rose    | 项目源码 | 文件源码
def __init__(self, longitude, latitude, age=0., sigma_age=0.0, **kwargs):

        if np.iterable(sigma_age) == 1:
            assert len(sigma_age) == 2  # upper and lower bounds
            self._age_type = 'uniform'
        else:
            self._age_type = 'gaussian'

        self._age = age
        self._sigma_age = sigma_age

        super(PaleomagneticPole, self).__init__(
            longitude, latitude, 1.0, **kwargs)
项目:BinarizationService    作者:jingchaoluan    | 项目源码 | 文件源码
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_)
项目:deep_ocr    作者:JinpengLI    | 项目源码 | 文件源码
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_)
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
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
项目:lambda-numba    作者:rlhotovy    | 项目源码 | 文件源码
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)
项目:soif    作者:ceyzeriat    | 项目源码 | 文件源码
def quantile(x, q, weights=None):
    """
    Like numpy.percentile, but:
    * Values of q are quantiles [0., 1.] rather than percentiles [0., 100.]
    * scalar q not supported (q must be iterable)
    * optional weights on x
    """
    if weights is None:
        return np.percentile(x, [100. * qi for qi in q])
    else:
        idx = np.argsort(x)
        xsorted = x[idx]
        cdf = np.add.accumulate(weights[idx])
        cdf /= cdf[-1]
        return np.interp(q, cdf, xsorted).tolist()
项目:spyking-circus-ort    作者:spyking-circus    | 项目源码 | 文件源码
def slice_templates_by_channel(self, channels):

        if not np.iterable(channels):
            channels = [channels]
        result = []
        for t in self.get():
            if t.channel in [channels]:
                result += [t]

        return result