示例#1
0
def is_boolean_array(value):
    """ 
    >>> from dimarray import DimArray
    >>> a = DimArray([1,2,3])
    >>> is_boolean_array(a)
    False
    >>> is_boolean_array(a>1)
    True
    """
    return (isinstance(value, np.ndarray) or is_DimArray(value)) \
            and value.dtype is np.dtype('bool')
示例#2
0
    def __getitem__(self, ix):
        """ 
        """
        #
        # check special cases
        #
        assert ix is not None, "index is None!"

        if self.position_index:
            return ix

        # boolean indexing ?
        if is_DimArray(ix):
            ix = ix.values

        if type(ix) in (np.ndarray,) and ix.dtype is np.dtype(bool):
            return ix

        # make sure (1,) is understood as 1 just as numpy would
        elif type(ix) is tuple:
            if len(ix) == 1:
                ix = ix[0]
        #    else:
        #        raise TypeError("index not understood: did you mean a `slice`?")

        #
        # look up corresponding numpy indices
        #
        # e.g. 45:56
        if type(ix) is slice:
            res = self.slice(ix)

        elif self._islist(ix):
            res = map(self.locate, ix)
            #res = [self.locate(i) for i in ix]

        else:
            res = self.locate(ix)

        return res
示例#3
0
def operation(func, o1, o2, reindex=True, broadcast=True, constructor=None):
    """ binary operation involving a DimArray objects

    Parameters
    ----------
    func : operator
    o1 : LHS operand: DimArray
    o2 : RHS operand: at least: be convertible by np.array())
    align : bool, optional
        if True, use pandas to align the axes
    constructor : class Constructor, optional
        if None, o1's class constructor (o1._constructor) is used instead

    Returns
    -------
    DimArray instance
    """

    if constructor is None:
        constructor = o1._constructor

    # second operand is not a DimArray: let numpy do the job 
    if not is_DimArray(o2): # isinstance
        if np.ndim(o2) > np.ndim(o1):
            raise ValueError("bad input: second operand's dimensions not documented")
        res = func(o1.values, np.array(o2))
        return constructor(res, o1.axes)

    # check for first operand (reverse operations)
    elif not is_DimArray(o1): # isinstance
        if np.ndim(o1) > np.ndim(o2):
            raise ValueError("bad input: second operand's dimensions not documented")
        res = func(np.array(o1), o2.values)
        return constructor(res, o2.axes)

    # both objects are dimarrays

    # check grid mapping and emit a warning if mismatch
    if hasattr(o1, 'grid_mapping') and hasattr(o2, 'grid_mapping') \
            and o1.grid_mapping != o2.grid_mapping:
                warnings.warn("binary op : grid mappings mismatch")

    # Align axes by re-indexing
    if reindex:
        o1, o2 = align_axes(o1, o2)

    # Align dimensions by adding new axes and transposing if necessary
    if broadcast:
        o1, o2 = align_dims(o1, o2)

    # make the new axes
    newaxes = o1.axes.copy()

    # ...make sure no singleton value is included
    for i, ax in enumerate(newaxes):
        if ax.values[0] is None:
            newaxes[i] = o2.axes[ax.name]

    res = func(o1.values, o2.values)

    return constructor(res, newaxes)
示例#4
0
def stack(arrays, axis=None, keys=None, align=False, **kwargs):
    """ stack arrays along a new dimension (raise error if already existing)

    Parameters
    ----------
    arrays : sequence or dict of arrays
    axis : str, optional
        new dimension along which to stack the array
    keys : array-like, optional
        stack axis values, useful if array is a sequence, or a non-ordered dictionary
    align : bool, optional
        if True, align axes prior to stacking (Default to False)
    **kwargs : optional key-word arguments passed to align, if align is True

    Returns
    -------
    DimArray : joint array

    See Also
    --------
    concatenate : join arrays along an existing dimension
    swapaxes : to modify the position of the newly inserted axis

    Examples
    --------
    >>> from dimarray import DimArray
    >>> a = DimArray([1,2,3])
    >>> b = DimArray([11,22,33])
    >>> stack([a, b], axis='stackdim', keys=['a','b'])
    dimarray: 6 non-null elements (0 null)
    0 / stackdim (2): 'a' to 'b'
    1 / x0 (3): 0 to 2
    array([[ 1,  2,  3],
           [11, 22, 33]])
    """
    assert not isinstance(axis, int), "axis must be a str (you are creating a new axis)"

    # make a sequence of arrays
    arrays, keys = _check_stack_args(arrays, keys)

    for a in arrays: 
        if not is_DimArray(a): raise TypeError('can only stack DimArray instances')

    # make sure the stacking dimension is OK (new)
    dims = get_dims(*arrays)
    axis = _check_stack_axis(axis, dims)

    # re-index axes if needed
    if align:
        kwargs['strict'] = True
        arrays = align_(arrays, **kwargs)

    # make it a numpy array
    data = [a.values for a in arrays]
    data = np.array(data)

    # new axis
    newaxis = Axis(keys, axis)

    # find common axes
    try: 
        axes = _get_axes(*arrays)
    except ValueError, msg: 
        if 'axes are not aligned' in repr(msg):
            msg = 'axes are not aligned\n ==> Try passing `align=True`' 
        raise ValueError(msg)