Python numpy.atleast_1d() Examples

The following are 30 code examples of numpy.atleast_1d(). 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 numpy , or try the search function .
Example #1
Source File: em.py    From typhon with MIT License 6 votes vote down vote up
def blackbody_radiance(self, T, spectral=True):
        """Calculate integrated radiance for blackbody at temperature T

        :param T: Temperature [K].  This can be either a python number, or
            a numpy ndarray, on a ureg quantity encompassing either.
        :param spectral: Parameter to control whether to return spectral
            radiance or radiance.  See self.integrate_radiances for
            details.

        Returns quantity ndarray with blackbody radiance in desired unit.
        Note that this is an ndarray with dimension (1,) even if you
        passin a scalar.
        """
        try:
            T = T.to("K")
        except AttributeError:
            T = ureg.Quantity(T, "K")
        T = ureg.Quantity(numpy.atleast_1d(T), T.u)
        # fails if T is multidimensional
        shp = T.shape
        return self.integrate_radiances(
            self.frequency, planck_f(
                self.frequency[numpy.newaxis, :],
                T.reshape((-1,))[:, numpy.newaxis]),
                spectral=spectral).reshape(shp) 
Example #2
Source File: stats.py    From lambda-packs with MIT License 6 votes vote down vote up
def _chk2_asarray(a, b, axis):
    if axis is None:
        a = np.ravel(a)
        b = np.ravel(b)
        outaxis = 0
    else:
        a = np.asarray(a)
        b = np.asarray(b)
        outaxis = axis

    if a.ndim == 0:
        a = np.atleast_1d(a)
    if b.ndim == 0:
        b = np.atleast_1d(b)

    return a, b, outaxis 
Example #3
Source File: filter_design.py    From lambda-packs with MIT License 6 votes vote down vote up
def lp2lp(b, a, wo=1.0):
    """
    Transform a lowpass filter prototype to a different frequency.

    Return an analog low-pass filter with cutoff frequency `wo`
    from an analog low-pass filter prototype with unity cutoff frequency, in
    transfer function ('ba') representation.

    """
    a, b = map(atleast_1d, (a, b))
    try:
        wo = float(wo)
    except TypeError:
        wo = float(wo[0])
    d = len(a)
    n = len(b)
    M = max((d, n))
    pwo = pow(wo, numpy.arange(M - 1, -1, -1))
    start1 = max((n - d, 0))
    start2 = max((d - n, 0))
    b = b * pwo[start1] / pwo[start2:]
    a = a * pwo[start1] / pwo[start1:]
    return normalize(b, a) 
Example #4
Source File: utils.py    From baseband with GNU General Public License v3.0 6 votes vote down vote up
def byte_array(pattern):
    """Convert the pattern to a byte array.

    Parameters
    ----------
    pattern : ~numpy.ndarray, bytes, int, or iterable of int
        Pattern to convert.  If a `~numpy.ndarray` or `bytes` instance,
        a byte array view is taken.  If an (iterable of) int, the integers
        need to be unsigned 32 bit and will be interpreted as little-endian.

    Returns
    -------
    byte_array : `~numpy.ndarray` of byte
        With any elements of pattern stored in little-endian order.
    """
    if isinstance(pattern, (np.ndarray, bytes)):
        # Quick turn-around for input that is OK already:
        return np.atleast_1d(pattern).view('u1')

    pattern = np.array(pattern, ndmin=1)
    if (pattern.dtype.kind not in 'uif'
            or pattern.min() < 0
            or pattern.max() >= 1 << 32):
        raise ValueError('values have to fit in 32 bit unsigned int.')
    return pattern.astype('<u4').view('u1') 
Example #5
Source File: minpack.py    From lambda-packs with MIT License 6 votes vote down vote up
def _check_func(checker, argname, thefunc, x0, args, numinputs,
                output_shape=None):
    res = atleast_1d(thefunc(*((x0[:numinputs],) + args)))
    if (output_shape is not None) and (shape(res) != output_shape):
        if (output_shape[0] != 1):
            if len(output_shape) > 1:
                if output_shape[1] == 1:
                    return shape(res)
            msg = "%s: there is a mismatch between the input and output " \
                  "shape of the '%s' argument" % (checker, argname)
            func_name = getattr(thefunc, '__name__', None)
            if func_name:
                msg += " '%s'." % func_name
            else:
                msg += "."
            msg += 'Shape should be %s but it is %s.' % (output_shape, shape(res))
            raise TypeError(msg)
    if issubdtype(res.dtype, inexact):
        dt = res.dtype
    else:
        dt = dtype(float)
    return shape(res), dt 
Example #6
Source File: test_linalg.py    From recruit with Apache License 2.0 6 votes vote down vote up
def do(self, a, b, tags):
        d = linalg.det(a)
        (s, ld) = linalg.slogdet(a)
        if asarray(a).dtype.type in (single, double):
            ad = asarray(a).astype(double)
        else:
            ad = asarray(a).astype(cdouble)
        ev = linalg.eigvals(ad)
        assert_almost_equal(d, multiply.reduce(ev, axis=-1))
        assert_almost_equal(s * np.exp(ld), multiply.reduce(ev, axis=-1))

        s = np.atleast_1d(s)
        ld = np.atleast_1d(ld)
        m = (s != 0)
        assert_almost_equal(np.abs(s[m]), 1)
        assert_equal(ld[~m], -inf) 
Example #7
Source File: _continuous_distns.py    From lambda-packs with MIT License 6 votes vote down vote up
def _munp(self, n, beta, m):
        """
        Returns the n-th non-central moment of the crystalball function.
        """
        N = 1.0 / (m/beta / (m-1) * np.exp(-beta**2 / 2.0) + _norm_pdf_C * _norm_cdf(beta))

        def n_th_moment(n, beta, m):
            """
            Returns n-th moment. Defined only if n+1 < m
            Function cannot broadcast due to the loop over n
            """
            A = (m/beta)**m * np.exp(-beta**2 / 2.0)
            B = m/beta - beta
            rhs = 2**((n-1)/2.0) * sc.gamma((n+1)/2) * (1.0 + (-1)**n * sc.gammainc((n+1)/2, beta**2 / 2))
            lhs = np.zeros(rhs.shape)
            for k in range(n + 1):
                lhs += sc.binom(n, k) * B**(n-k) * (-1)**k / (m - k - 1) * (m/beta)**(-m + k + 1)
            return A * lhs + rhs

        return N * _lazywhere(np.atleast_1d(n + 1 < m),
                              (n, beta, m),
                              np.vectorize(n_th_moment, otypes=[np.float]),
                              np.inf) 
Example #8
Source File: parameters.py    From buzzard with Apache License 2.0 6 votes vote down vote up
def normalize_channels_parameter(channels, channel_count):
    if channels is None:
        if channel_count == 1:
            return [0], True
        else:
            return list(range(channel_count)), False

    indices = np.arange(channel_count)
    indices = indices[channels]
    indices = np.atleast_1d(indices)

    if isinstance(channels, slice):
        return indices.tolist(), False

    channels = np.asarray(channels)
    if not np.issubdtype(channels.dtype, np.number):
        raise TypeError('`channels` should be None or int or slice or list of int')
    if channels.ndim == 0:
        assert len(indices) == 1
        return indices.tolist(), True
    return indices.tolist(), False 
Example #9
Source File: partition.py    From mars with Apache License 2.0 6 votes vote down vote up
def _validate_partition_arguments(a, kth, axis, kind, order, kw):
    a = astensor(a)
    if axis is None:
        a = a.flatten()
        axis = 0
    else:
        axis = validate_axis(a.ndim, axis)
    if isinstance(kth, (Base, Entity)):
        kth = astensor(kth)
        _check_kth_dtype(kth.dtype)
    else:
        kth = np.atleast_1d(kth)
        kth = _validate_kth_value(kth, a.shape[axis])
    if kth.ndim > 1:
        raise ValueError('object too deep for desired array')
    if kind != 'introselect':
        raise ValueError('{} is an unrecognized kind of select'.format(kind))
    # if a is structure type and order is not None
    order = validate_order(a.dtype, order)
    need_align = kw.pop('need_align', None)
    if len(kw) > 0:
        raise TypeError('partition() got an unexpected keyword '
                        'argument \'{}\''.format(next(iter(kw))))

    return a, kth, axis, kind, order, need_align 
Example #10
Source File: filter_design.py    From lambda-packs with MIT License 5 votes vote down vote up
def lp2bs(b, a, wo=1.0, bw=1.0):
    """
    Transform a lowpass filter prototype to a bandstop filter.

    Return an analog band-stop filter with center frequency `wo` and
    bandwidth `bw` from an analog low-pass filter prototype with unity
    cutoff frequency, in transfer function ('ba') representation.

    """
    a, b = map(atleast_1d, (a, b))
    D = len(a) - 1
    N = len(b) - 1
    artype = mintypecode((a, b))
    M = max([N, D])
    Np = M + M
    Dp = M + M
    bprime = numpy.zeros(Np + 1, artype)
    aprime = numpy.zeros(Dp + 1, artype)
    wosq = wo * wo
    for j in range(Np + 1):
        val = 0.0
        for i in range(0, N + 1):
            for k in range(0, M - i + 1):
                if i + 2 * k == j:
                    val += (comb(M - i, k) * b[N - i] *
                            (wosq) ** (M - i - k) * bw ** i)
        bprime[Np - j] = val
    for j in range(Dp + 1):
        val = 0.0
        for i in range(0, D + 1):
            for k in range(0, M - i + 1):
                if i + 2 * k == j:
                    val += (comb(M - i, k) * a[D - i] *
                            (wosq) ** (M - i - k) * bw ** i)
        aprime[Dp - j] = val

    return normalize(bprime, aprime) 
Example #11
Source File: observable_array.py    From paramz with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __new__(cls, input_array, *a, **kw):
        # allways make a copy of input paramters, as we need it to be in C order:
        if not isinstance(input_array, ObsAr):
            try:
                # try to cast ints to floats
                obj = np.atleast_1d(np.require(input_array, dtype=np.float_, requirements=['W', 'C'])).view(cls)
            except ValueError:
                # do we have other dtypes in the array?
                obj = np.atleast_1d(np.require(input_array, requirements=['W', 'C'])).view(cls)
        else: obj = input_array
        super(ObsAr, obj).__init__(*a, **kw)
        return obj 
Example #12
Source File: filter_design.py    From lambda-packs with MIT License 5 votes vote down vote up
def lp2bp(b, a, wo=1.0, bw=1.0):
    """
    Transform a lowpass filter prototype to a bandpass filter.

    Return an analog band-pass filter with center frequency `wo` and
    bandwidth `bw` from an analog low-pass filter prototype with unity
    cutoff frequency, in transfer function ('ba') representation.

    """
    a, b = map(atleast_1d, (a, b))
    D = len(a) - 1
    N = len(b) - 1
    artype = mintypecode((a, b))
    ma = max([N, D])
    Np = N + ma
    Dp = D + ma
    bprime = numpy.zeros(Np + 1, artype)
    aprime = numpy.zeros(Dp + 1, artype)
    wosq = wo * wo
    for j in range(Np + 1):
        val = 0.0
        for i in range(0, N + 1):
            for k in range(0, i + 1):
                if ma - i + 2 * k == j:
                    val += comb(i, k) * b[N - i] * (wosq) ** (i - k) / bw ** i
        bprime[Np - j] = val
    for j in range(Dp + 1):
        val = 0.0
        for i in range(0, D + 1):
            for k in range(0, i + 1):
                if ma - i + 2 * k == j:
                    val += comb(i, k) * a[D - i] * (wosq) ** (i - k) / bw ** i
        aprime[Dp - j] = val

    return normalize(bprime, aprime) 
Example #13
Source File: filter_design.py    From lambda-packs with MIT License 5 votes vote down vote up
def lp2hp(b, a, wo=1.0):
    """
    Transform a lowpass filter prototype to a highpass filter.

    Return an analog high-pass filter with cutoff frequency `wo`
    from an analog low-pass filter prototype with unity cutoff frequency, in
    transfer function ('ba') representation.

    """
    a, b = map(atleast_1d, (a, b))
    try:
        wo = float(wo)
    except TypeError:
        wo = float(wo[0])
    d = len(a)
    n = len(b)
    if wo != 1:
        pwo = pow(wo, numpy.arange(max((d, n))))
    else:
        pwo = numpy.ones(max((d, n)), b.dtype.char)
    if d >= n:
        outa = a[::-1] * pwo
        outb = resize(b, (d,))
        outb[n:] = 0.0
        outb[:n] = b[::-1] * pwo[:n]
    else:
        outb = b[::-1] * pwo
        outa = resize(a, (n,))
        outa[d:] = 0.0
        outa[:d] = a[::-1] * pwo[:d]

    return normalize(outb, outa) 
Example #14
Source File: ltisys.py    From lambda-packs with MIT License 5 votes vote down vote up
def num(self, num):
        self._num = atleast_1d(num)

        # Update dimensions
        if len(self.num.shape) > 1:
            self.outputs, self.inputs = self.num.shape
        else:
            self.outputs = 1
            self.inputs = 1 
Example #15
Source File: ltisys.py    From lambda-packs with MIT License 5 votes vote down vote up
def den(self, den):
        self._den = atleast_1d(den) 
Example #16
Source File: ltisys.py    From lambda-packs with MIT License 5 votes vote down vote up
def poles(self, poles):
        self._poles = atleast_1d(poles) 
Example #17
Source File: np_utils.py    From CAPTCHA-breaking with MIT License 5 votes vote down vote up
def normalize(a, axis=-1, order=2):
    l2 = np.atleast_1d(np.linalg.norm(a, order, axis))
    l2[l2 == 0] = 1
    return a / np.expand_dims(l2, axis) 
Example #18
Source File: transform.py    From bop_toolkit with MIT License 5 votes vote down vote up
def vector_norm(data, axis=None, out=None):
  """Return length, i.e. Euclidean norm, of ndarray along axis.

  >>> v = numpy.random.random(3)
  >>> n = vector_norm(v)
  >>> numpy.allclose(n, numpy.linalg.norm(v))
  True
  >>> v = numpy.random.rand(6, 5, 3)
  >>> n = vector_norm(v, axis=-1)
  >>> numpy.allclose(n, numpy.sqrt(numpy.sum(v*v, axis=2)))
  True
  >>> n = vector_norm(v, axis=1)
  >>> numpy.allclose(n, numpy.sqrt(numpy.sum(v*v, axis=1)))
  True
  >>> v = numpy.random.rand(5, 4, 3)
  >>> n = numpy.empty((5, 3))
  >>> vector_norm(v, axis=1, out=n)
  >>> numpy.allclose(n, numpy.sqrt(numpy.sum(v*v, axis=1)))
  True
  >>> vector_norm([])
  0.0
  >>> vector_norm([1])
  1.0

  """
  data = numpy.array(data, dtype=numpy.float64, copy=True)
  if out is None:
    if data.ndim == 1:
      return math.sqrt(numpy.dot(data, data))
    data *= data
    out = numpy.atleast_1d(numpy.sum(data, axis=axis))
    numpy.sqrt(out, out)
    return out
  else:
    data *= data
    numpy.sum(data, axis=axis, out=out)
    numpy.sqrt(out, out) 
Example #19
Source File: distance.py    From lambda-packs with MIT License 5 votes vote down vote up
def _validate_vector(u, dtype=None):
    # XXX Is order='c' really necessary?
    u = np.asarray(u, dtype=dtype, order='c').squeeze()
    # Ensure values such as u=1 and u=[1] still return 1-D arrays.
    u = np.atleast_1d(u)
    if u.ndim > 1:
        raise ValueError("Input vector should be 1-D.")
    return u 
Example #20
Source File: states.py    From westpa with MIT License 5 votes vote down vote up
def __init__(self, label, pcoord, state_id=None):
        self.label = label
        self.pcoord = numpy.atleast_1d(pcoord)
        self.state_id = state_id 
Example #21
Source File: signaltools.py    From lambda-packs with MIT License 5 votes vote down vote up
def medfilt(volume, kernel_size=None):
    """
    Perform a median filter on an N-dimensional array.

    Apply a median filter to the input array using a local window-size
    given by `kernel_size`.

    Parameters
    ----------
    volume : array_like
        An N-dimensional input array.
    kernel_size : array_like, optional
        A scalar or an N-length list giving the size of the median filter
        window in each dimension.  Elements of `kernel_size` should be odd.
        If `kernel_size` is a scalar, then this scalar is used as the size in
        each dimension. Default size is 3 for each dimension.

    Returns
    -------
    out : ndarray
        An array the same size as input containing the median filtered
        result.

    """
    volume = atleast_1d(volume)
    if kernel_size is None:
        kernel_size = [3] * volume.ndim
    kernel_size = asarray(kernel_size)
    if kernel_size.shape == ():
        kernel_size = np.repeat(kernel_size.item(), volume.ndim)

    for k in range(volume.ndim):
        if (kernel_size[k] % 2) != 1:
            raise ValueError("Each element of kernel_size should be odd.")

    domain = ones(kernel_size)

    numels = product(kernel_size, axis=0)
    order = numels // 2
    return sigtools._order_filterND(volume, domain, order) 
Example #22
Source File: states.py    From westpa with MIT License 5 votes vote down vote up
def __init__(self, label, probability, pcoord=None, auxref=None, state_id=None):
        self.label = label
        self.probability = probability         
        self.pcoord = numpy.atleast_1d(pcoord)
        self.auxref = auxref 
        self.state_id = state_id 
Example #23
Source File: states.py    From westpa with MIT License 5 votes vote down vote up
def __init__(self, state_id, basis_state_id, iter_created, iter_used=None, 
                 istate_type=None, istate_status=None,
                 pcoord=None, 
                 basis_state=None):
        self.state_id = state_id
        self.basis_state_id = basis_state_id
        self.basis_state=basis_state
        self.istate_type = istate_type
        self.istate_status = istate_status
        self.iter_created = iter_created
        self.iter_used = iter_used         
        self.pcoord = numpy.atleast_1d(pcoord) 
Example #24
Source File: index_lib.py    From mars with Apache License 2.0 5 votes vote down vote up
def preprocess(self,
                   index_info: IndexInfo,
                   context: IndexHandlerContext) -> None:
        tileable = context.tileable
        check_chunks_unknown_shape([tileable], TilesError)

        input_axis = index_info.input_axis
        if tileable.ndim == 2:
            index_value = [tileable.index_value, tileable.columns_value][input_axis]
        else:
            index_value = tileable.index_value
        cum_nsplit = [0] + np.cumsum(tileable.nsplits[input_axis]).tolist()
        if index_value.has_value():
            # turn label-based fancy index into position-based
            pd_index = index_value.to_pandas()
            positions = convert_labels_into_positions(pd_index, index_info.raw_index)
            split_info = split_indexes_into_chunks([tileable.nsplits[input_axis]],
                                                   [positions])
            chunk_index_to_pos = split_info[0]
            is_asc_sorted = split_info[-1]

            # convert back to labels for chunk_index
            chunk_index_to_labels = dict()
            for chunk_index, pos in chunk_index_to_pos.items():
                # chunk_index and pos are all list with 1 element
                abs_pos = pos[0] + cum_nsplit[chunk_index[0]]
                chunk_labels = to_numpy(pd_index[abs_pos])
                chunk_index_to_labels[chunk_index[0]] = chunk_labels

            index_info.is_label_asc_sorted = is_asc_sorted
            index_info.chunk_index_to_labels = chunk_index_to_labels
        else:
            index = index_info.raw_index
            if np.isscalar(index):
                # delegation from label index handler
                index = np.atleast_1d(index)
            # does not know the right positions, need postprocess always
            index_info.is_label_asc_sorted = False
            # do df.loc on each chunk
            index_info.chunk_index_to_labels = \
                {i: index for i in range(tileable.chunk_shape[input_axis])} 
Example #25
Source File: _utils.py    From dexplo with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def try_to_squeeze_array(arr: ndarray) -> ndarray:
    if arr.ndim == 1:
        return arr
    if arr.ndim == 2 and (arr.shape[0] == 1 or arr.shape[1] == 1):
        return np.atleast_1d(arr.squeeze())
    else:
        raise ValueError('Array must be one dimensional or two dimensional '
                         'with 1 column') 
Example #26
Source File: calcs.py    From mlearn with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _parse(self):
        element = np.atleast_1d(_read_dump('dump.element', 'unicode'))
        b = np.atleast_2d(_read_dump('dump.sna'))
        db = np.atleast_2d(_read_dump('dump.snad'))
        vb = np.atleast_2d(_read_dump('dump.snav'))
        return b, db, vb, element 
Example #27
Source File: tools.py    From burnman with GNU General Public License v2.0 5 votes vote down vote up
def unit_normalize(a, order=2, axis=-1):
    """
    Calculates the L2 normalized array of numpy array a
    of a given order and along a given axis.
    """
    l2 = np.atleast_1d(np.apply_along_axis(np.linalg.norm, axis, a, order))

    l2[l2==0] = 1
    return a / np.expand_dims(l2, axis)[0][0] 
Example #28
Source File: interpolate_wrapper.py    From lambda-packs with MIT License 5 votes vote down vote up
def atleast_1d_and_contiguous(ary, dtype=np.float64):
    return np.atleast_1d(np.ascontiguousarray(ary, dtype)) 
Example #29
Source File: transformations.py    From cozmo_driver with Apache License 2.0 5 votes vote down vote up
def vector_norm(data, axis=None, out=None):
    """Return length, i.e. eucledian norm, of ndarray along axis.

    >>> v = numpy.random.random(3)
    >>> n = vector_norm(v)
    >>> numpy.allclose(n, numpy.linalg.norm(v))
    True
    >>> v = numpy.random.rand(6, 5, 3)
    >>> n = vector_norm(v, axis=-1)
    >>> numpy.allclose(n, numpy.sqrt(numpy.sum(v*v, axis=2)))
    True
    >>> n = vector_norm(v, axis=1)
    >>> numpy.allclose(n, numpy.sqrt(numpy.sum(v*v, axis=1)))
    True
    >>> v = numpy.random.rand(5, 4, 3)
    >>> n = numpy.empty((5, 3), dtype=numpy.float64)
    >>> vector_norm(v, axis=1, out=n)
    >>> numpy.allclose(n, numpy.sqrt(numpy.sum(v*v, axis=1)))
    True
    >>> vector_norm([])
    0.0
    >>> vector_norm([1.0])
    1.0

    """
    data = numpy.array(data, dtype=numpy.float64, copy=True)
    if out is None:
        if data.ndim == 1:
            return math.sqrt(numpy.dot(data, data))
        data *= data
        out = numpy.atleast_1d(numpy.sum(data, axis=axis))
        numpy.sqrt(out, out)
        return out
    else:
        data *= data
        numpy.sum(data, axis=axis, out=out)
        numpy.sqrt(out, out) 
Example #30
Source File: interpolate_wrapper.py    From lambda-packs with MIT License 5 votes vote down vote up
def nearest(x, y, new_x):
    """
    Rounds each new x to nearest input x and returns corresponding input y.

    Parameters
    ----------
    x : array_like
        Independent values.
    y : array_like
        Dependent values.
    new_x : array_like
        The x values to return the interpolate y values.

    Returns
    -------
    nearest : ndarray
        Rounds each `new_x` to nearest `x` and returns the corresponding `y`.

    """
    shifted_x = np.concatenate((np.array([x[0]-1]), x[0:-1]))

    midpoints_of_x = atleast_1d_and_contiguous(.5*(x + shifted_x))
    new_x = atleast_1d_and_contiguous(new_x)

    TINY = 1e-10
    indices = np.searchsorted(midpoints_of_x, new_x+TINY)-1
    indices = np.atleast_1d(np.clip(indices, 0, np.Inf).astype(int))
    new_y = np.take(y, indices, axis=-1)

    return new_y