Exemple #1
0
 def __rdiv__(self, other):
     r = None
     if isinstance(other, MIArray):      
         r = MIArray(ArrayMath.div(other.array, self.array))
     else:
         r = MIArray(ArrayMath.div(other, self.array))
     return r
Exemple #2
0
 def __mul__(self, other):
     r = None
     if isinstance(other, MIArray):      
         r = MIArray(ArrayMath.mul(self.array, other.array))
     else:
         r = MIArray(ArrayMath.mul(self.array, other))
     return r
Exemple #3
0
    def median(self, axis=None):
        '''
        Compute tha median along the specified axis.

        :param axis: (*int*) Axis along which the standard deviation is computed. 
            The default is to compute the standard deviation of the flattened array.
        
        returns: (*array_like*) Median result
        '''
        if axis is None:
            return ArrayMath.median(self.array)
        else:
            return MIArray(ArrayMath.median(self.array, axis))
Exemple #4
0
 def inpolygon(self, x, y, polygon):
     if isinstance(polygon, tuple):
         x_p = polygon[0]
         y_p = polygon[1]
         if isinstance(x_p, MIArray):
             x_p = x_p.aslist()
         if isinstance(y_p, MIArray):
             y_p = y_p.aslist()
         return MIArray(ArrayMath.inPolygon(self.array, x.aslist(), y.aslist(), x_p, y_p))
     else:
         if isinstance(polygon, MILayer):
             polygon = polygon.layer
         return MIArray(ArrayMath.inPolygon(self.array, x.aslist(), y.aslist(), polygon))
Exemple #5
0
    def sum(self, axis=None):
        '''
        Sum of array elements over a given axis.

        :param axis: (*int*) Axis along which the standard deviation is computed. 
            The default is to compute the standard deviation of the flattened array.
        
        returns: (*array_like*) Sum result
        '''
        if axis is None:
            return ArrayMath.sum(self.array)
        else:
            r = ArrayMath.sum(self.array, axis)
            return MIArray(r)
Exemple #6
0
 def max(self, axis=None):
     '''
     Get maximum value along an axis.
     
     :param axis: (*int*) Axis along which the maximum is computed. The default is to 
         compute the maximum of the flattened array.
         
     :returns: Maximum values.
     '''
     if axis is None:
         r = ArrayMath.max(self.array)
         return r
     else:
         r = ArrayMath.max(self.array, axis)
         return MIArray(r)
Exemple #7
0
 def argmax(self, axis=None):
     '''
     Returns the indices of the minimum values along an axis.
     
     :param axis: (*int*) By default, the index is into the flattened array, otherwise 
         along the specified axis.
         
     :returns: Array of indices into the array. It has the same shape as a.shape with the 
         dimension along axis removed.
     '''
     if axis is None:
         r = ArrayMath.argMax(self.array)
         return r
     else:
         r = ArrayMath.argMax(self.array, axis)
         return MIArray(r)
Exemple #8
0
 def contains_nan(self):
     '''
     Check if the array contains nan value.
     
     :returns: (*boolean*) True if contains nan, otherwise return False.
     '''
     return ArrayMath.containsNaN(self.array)
Exemple #9
0
    def sign(self):
        '''
        Returns an element-wise indication of the sign of a number.

        The sign function returns -1 if x < 0, 0 if x==0, 1 if x > 0. nan is returned for nan inputs.
        '''
        return MIArray(ArrayMath.sign(self.array))
Exemple #10
0
 def prod(self):
     '''
     Return the product of array elements.
     
     :returns: (*float*) Produce value.
     '''
     return ArrayMath.prodDouble(self.array)
Exemple #11
0
 def std(self, axis=None):
     '''
     Compute the standard deviation along the specified axis.
 
     :param x: (*array_like or list*) Input values.
     :param axis: (*int*) Axis along which the standard deviation is computed. 
         The default is to compute the standard deviation of the flattened array.
     
     returns: (*array_like*) Standart deviation result.
     '''
     if axis is None:
         r = ArrayMath.std(self.array)
         return r
     else:
         r = ArrayMath.std(self.array, axis)
         return MIArray(r)
Exemple #12
0
 def abs(self):
     '''
     Calculate the absolute value element-wise.
     
     :returns: An array containing the absolute value of each element in x. 
         For complex input, a + ib, the absolute value is \sqrt{ a^2 + b^2 }.
     '''
     return MIArray(ArrayMath.abs(self.array))
Exemple #13
0
 def take(self, indices):
     '''
     Take elements from an array along an axis.
     
     :param indices: (*array_like*) The indices of the values to extract.
     
     :returns: (*array*) The returned array has the same type as a.
     '''
     ilist = [indices]
     r = ArrayMath.take(self.array, ilist)
     return MIArray(r)
Exemple #14
0
 def transpose(self):
     '''
     Transpose 2-D array.
     
     :returns: Transposed array.
     '''
     if self.ndim == 1:
         return self[:]
     dim1 = 0
     dim2 = 1
     r = ArrayMath.transpose(self.asarray(), dim1, dim2)
     return MIArray(r)
Exemple #15
0
 def maskout(self, x, y, polygon, fill_value=Double.NaN):
     if isinstance(x, MIArray):
         xl = x.aslist()
     else:
         xl = x
     if isinstance(y, MIArray):
         yl = y.aslist()
     else:
         yl = y
     if isinstance(polygon, MILayer):
         polygon = polygon.layer
     return MIArray(ArrayMath.maskout(self.array, xl, yl, polygon, fill_value))
Exemple #16
0
 def dot(self, other):
     """
     Matrix multiplication.
     
     :param other: (*2D or 1D Array*) Matrix or vector b.
     
     :returns: Result Matrix or vector.
     """  
     if isinstance(other, list):
         other = array(other)
     r = ArrayMath.dot(self.array, other.array)
     return MIArray(r)
Exemple #17
0
    def __setitem__(self, indices, value):
        #print type(indices) 
        if isinstance(indices, (MIArray, DimArray)):
            ArrayMath.setValue(self.asarray(), indices.asarray(), value)
            return None
        
        if not isinstance(indices, tuple):
            inds = []
            inds.append(indices)
            indices = inds
        
        if self.rank == 0:
            self.array.array.setObject(0, value)
            return None
        
        if len(indices) != self.rank:
            print 'indices must be ' + str(self.rank) + ' dimensions!'
            return None

        ranges = []
        flips = []        
        for i in range(0, self.rank):   
            if isinstance(indices[i], int):
                sidx = indices[i]
                eidx = indices[i]
                step = 1
            else:
                sidx = 0 if indices[i].start is None else indices[i].start
                eidx = self.shape[i]-1 if indices[i].stop is None else indices[i].stop
                step = 1 if indices[i].step is None else indices[i].step
            if step < 0:
                step = abs(step)
                flips.append(i)
            rr = Range(sidx, eidx, step)
            ranges.append(rr)
    
        if isinstance(value, (MIArray, DimArray)):
            value = value.asarray()
        r = ArrayMath.setSection(self.array.array, ranges, value)
        self.array.array = r
Exemple #18
0
 def in_values(self, other):
     '''
     Return the array with the value of 1 when the element value
     in the list other, otherwise set value as 0.
     
     :param other: (*list or array*) List value.
     
     :returns: (*array*) Result array.
     '''
     if not isinstance(other, (list, tuple)):
         other = other.aslist()
     r = MIArray(ArrayMath.inValues(self.array, other))
     return r
Exemple #19
0
    def __getitem__(self, indices):
        #print type(indices)            
        if not isinstance(indices, tuple):
            inds = []
            inds.append(indices)
            indices = inds
            
        if self.rank == 0:
            return self
        
        if len(indices) != self.rank:
            print 'indices must be ' + str(self.rank) + ' dimensions!'
            return None

        ranges = []
        flips = []
        iszerodim = True
        for i in range(0, self.rank):   
            if isinstance(indices[i], int):
                sidx = indices[i]
                eidx = indices[i]
                step = 1
            else:
                sidx = 0 if indices[i].start is None else indices[i].start
                eidx = self.getshape()[i]-1 if indices[i].stop is None else indices[i].stop-1
                step = 1 if indices[i].step is None else indices[i].step
            if sidx != eidx:
                iszerodim = False
            if step < 0:
                step = abs(step)
                flips.append(i)
            if sidx >= self.shape[i]:
                raise IndexError()
            rr = Range(sidx, eidx, step)
            ranges.append(rr)
        r = ArrayMath.section(self.array, ranges)
        if iszerodim:
            return r.getObject(0)
        else:
            for i in flips:
                r = r.flip(i)
            rr = Array.factory(r.getDataType(), r.getShape());
            MAMath.copy(rr, r);
            return MIArray(rr)
Exemple #20
0
def linregress(x, y, outvdn=False):
    '''
    Calculate a linear least-squares regression for two sets of measurements.
    
    :param x, y: (*array_like*) Two sets of measurements. Both arrays should have the same length.
    :param outvdn: (*boolean*) Output validate data number or not. Default is False.
    
    :returns: Result slope, intercept, relative coefficient, two-sided p-value for a hypothesis test 
        whose null hypothesis is that the slope is zero, standard error of the estimated gradient, 
        validate data number (remove NaN values).
    '''
    if isinstance(x, list):
        x = MIArray(ArrayUtil.array(x))
    if isinstance(y, list):
        y = MIArray(ArrayUtil.array(y))
    r = ArrayMath.lineRegress(x.asarray(), y.asarray())
    if outvdn:
        return r[0], r[1], r[2], r[3], r[4], r[5]
    else:
        return r[0], r[1], r[2], r[3], r[4]
Exemple #21
0
 def join(self, b, dimidx):
     r = ArrayMath.join(self.array.array, b.array.array, dimidx)
     dima = self.dimvalue(dimidx)
     dimb = b.dimvalue(dimidx)
     dimr = []
     if dima[0] < dimb[0]:
         for i in range(0, len(dima)):
             dimr.append(dima[i])
         for i in range(0, len(dimb)):
             dimr.append(dimb[i])
     else:
         for i in range(0, len(dimb)):
             dimr.append(dimb[i])
         for i in range(0, len(dima)):
             dimr.append(dima[i])
     rdims = []
     for i in range(0, len(self.dims)):
         if i == dimidx:
             ndim = Dimension()
             ndim.setDimValues(dimr)
             rdims.append(ndim)
         else:
             rdims.append(self.dims[i])
     return DimArray(MIArray(r), rdims, self.fill_value, self.proj)
Exemple #22
0
 def join(self, b, dimidx):
     r = ArrayMath.join(self.array.array, b.array.array, dimidx)
     dima = self.dimvalue(dimidx)
     dimb = b.dimvalue(dimidx)
     dimr = []
     if dima[0] < dimb[0]:
         for i in range(0, len(dima)):
             dimr.append(dima[i])
         for i in range(0, len(dimb)):
             dimr.append(dimb[i])
     else:
         for i in range(0, len(dimb)):
             dimr.append(dimb[i])
         for i in range(0, len(dima)):
             dimr.append(dima[i])
     rdims = []
     for i in range(0, len(self.dims)):
         if i == dimidx:
             ndim = Dimension()
             ndim.setDimValues(dimr)
             rdims.append(ndim)
         else:
             rdims.append(self.dims[i])
     return DimArray(MIArray(r), rdims, self.fill_value, self.proj)
Exemple #23
0
 def log10(self):
     return MIArray(ArrayMath.log10(self.array))
Exemple #24
0
 def asin(self):
     return MIArray(ArrayMath.asin(self.array))
Exemple #25
0
 def atan(self):
     return MIArray(ArrayMath.atan(self.array))
Exemple #26
0
 def __invert__(self):
     other = MIArray.__value_other(self, other)
     r = MIArray(ArrayMath.bitInvert(self.array))
     return r
Exemple #27
0
 def ave(self, fill_value=None):
     if fill_value == None:
         return ArrayMath.aveDouble(self.array)
     else:
         return ArrayMath.aveDouble(self.array, fill_value)
Exemple #28
0
 def median(self, axis=None):
     if axis is None:
         return ArrayMath.median(self.array)
     else:
         return MIArray(ArrayMath.median(self.array, axis))
Exemple #29
0
 def __and__(self, other):
     other = MIArray.__value_other(self, other)
     r = MIArray(ArrayMath.bitAnd(self.array, other))
     return r
Exemple #30
0
 def join(self, b, dimidx):
     r = ArrayMath.join(self.array, b.array, dimidx)
     return MIArray(r)
Exemple #31
0
 def log10(self):
     return MIArray(ArrayMath.log10(self.array))
Exemple #32
0
    def __getitem__(self, indices):
        #print type(indices)            
        if not isinstance(indices, tuple):
            inds = []
            inds.append(indices)
            indices = inds
            
        allint = True
        aindex = self.array.getIndex()
        i = 0
        for ii in indices:
            if isinstance(ii, int):
                if ii < 0:
                    ii = self.shape[i] + ii
                aindex.setDim(i, ii)
            else:
                allint = False
                break;
            i += 1
        if allint:
            return self.array.getObject(aindex)
            
        if self.ndim == 0:
            return self
        
        if len(indices) != self.ndim:
            print 'indices must be ' + str(self.ndim) + ' dimensions!'
            raise IndexError()

        ranges = []
        flips = []
        onlyrange = True
        alllist = True
        isempty = False
        nshape = []
        for i in range(0, self.ndim):  
            k = indices[i]
            if isinstance(k, int):
                if k < 0:
                    k = self._shape[i] + k
                sidx = k
                eidx = k
                step = 1
                alllist = False
            elif isinstance(k, slice):
                sidx = 0 if k.start is None else k.start
                if sidx < 0:
                    sidx = self._shape[i] + sidx
                eidx = self._shape[i] if k.stop is None else k.stop
                if eidx < 0:
                    eidx = self._shape[i] + eidx
                eidx -= 1                    
                step = 1 if k.step is None else k.step
                alllist = False
            elif isinstance(k, (list, tuple, MIArray)):
                if isinstance(k, MIArray):
                    k = k.aslist()
                if isinstance(k[0], bool):
                    kk = []
                    for i in range(len(k)):
                        if k[i]:
                            kk.append(i)
                    k = kk                        
                onlyrange = False
                ranges.append(k)
                continue
            else:
                print k
                return None
            if step < 0:
                step = abs(step)
                flips.append(i)
                if eidx < sidx:
                    tempidx = sidx
                    sidx = eidx + 2
                    eidx = tempidx
            if sidx >= self.shape[i]:
                raise IndexError()
            if eidx < sidx:
                isempty = True
            else:
                rr = Range(sidx, eidx, step)
                ranges.append(rr)
            nshape.append(eidx - sidx + 1 if eidx - sidx >= 0 else 0)

        if isempty:
            r = ArrayUtil.zeros(nshape, 'int')
            return MIArray(r)
            
        if onlyrange:
            r = ArrayMath.section(self.array, ranges)
        else:
            if alllist:
                r = ArrayMath.takeValues(self.array, ranges)
            else:
                r = ArrayMath.take(self.array, ranges)
        if r.getSize() == 1:
            r = r.getObject(0)
            if isinstance(r, Complex):
                return complex(r.getReal(), r.getImaginary())
            else:
                return r
        else:
            for i in flips:
                r = r.flip(i)
            rr = Array.factory(r.getDataType(), r.getShape());
            MAMath.copy(rr, r);
            return MIArray(rr)
Exemple #33
0
 def __invert__(self):
     if isinstance(other, MIArray):
         other = other.array
     r = MIArray(ArrayMath.bitInvert(self.array))
     return r
Exemple #34
0
 def __rshift__(self, other):
     if isinstance(other, MIArray):
         other = other.array
     r = MIArray(ArrayMath.rightShift(self.array, other))
     return r
Exemple #35
0
 def tolist(self):
     '''
     Convert to a list
     '''
     r = ArrayMath.asList(self.array)
     return list(r)
Exemple #36
0
 def aslist(self):
     r = ArrayMath.asList(self.array)
     return list(r)
Exemple #37
0
 def tolist(self):
     '''
     Convert to a list
     '''
     r = ArrayMath.asList(self.array)
     return list(r)
Exemple #38
0
 def __ne__(self, other):
     other = MIArray.__value_other(self, other)
     r = MIArray(ArrayMath.notEqual(self.array, other))
     return r
Exemple #39
0
 def join(self, b, dimidx):
     r = ArrayMath.join(self.array, b.array, dimidx)
     return MIArray(r)
Exemple #40
0
 def atan(self):
     return MIArray(ArrayMath.atan(self.array))
Exemple #41
0
 def __eq__(self, other):
     other = MIArray.__value_other(self, other)
     r = MIArray(ArrayMath.equal(self.array, other))
     return r
Exemple #42
0
 def aslist(self):
     return ArrayMath.asList(self.array.array)
Exemple #43
0
 def __ge__(self, other):
     other = MIArray.__value_other(self, other)
     r = MIArray(ArrayMath.greaterThanOrEqual(self.array, other))
     return r
Exemple #44
0
    def __getitem__(self, indices):
        #print type(indices)
        if not isinstance(indices, tuple):
            inds = []
            inds.append(indices)
            indices = inds
        
        if len(indices) != self.ndim:
            print 'indices must be ' + str(self.ndim) + ' dimensions!'
            return None
            
        #origin = []
        #size = []
        #stride = []
        dims = []
        ranges = []
        flips = []
        iszerodim = True
        for i in range(0, self.ndim):  
            k = indices[i]
            if isinstance(indices[i], int):
                sidx = k
                eidx = k
                step = 1                
            elif isinstance(k, slice):
                sidx = 0 if k.start is None else k.start
                eidx = self.dims[i].getLength()-1 if k.stop is None else k.stop-1
                step = 1 if k.step is None else k.step
            elif isinstance(k, tuple) or isinstance(k, list):
                dim = self.dims[i]
                sidx = dim.getValueIndex(k[0])
                if len(k) == 1:
                    eidx = sidx
                    step = 1
                else:                    
                    eidx = dim.getValueIndex(k[1])
                    if len(k) == 2:
                        step = 1
                    else:
                        step = int(k[2] / dim.getDeltaValue)
            else:
                print k
                return None

            if sidx >= self.shape[i]:
                raise IndexError()
                
            if sidx != eidx:
                iszerodim = False
            if step < 0:
                step = abs(step)
                flips.append(i)
            rr = Range(sidx, eidx, step)
            ranges.append(rr)
            #origin.append(sidx)
            n = eidx - sidx + 1
            #size.append(n)
            #stride.append(step)
            if n > 1:
                dim = self.dims[i]
                dims.append(dim.extract(sidx, eidx, step))
                    
        #r = ArrayMath.section(self.array.array, origin, size, stride)
        r = ArrayMath.section(self.array.array, ranges)
        if iszerodim:
            return r.getObject(0)
        else:
            for i in flips:
                r = r.flip(i)
            rr = Array.factory(r.getDataType(), r.getShape());
            MAMath.copy(rr, r);
            array = MIArray(rr)
            data = DimArray(array, dims, self.fill_value, self.proj)
            return data
Exemple #45
0
 def __xor__(self, other):
     other = MIArray.__value_other(self, other)
     r = MIArray(ArrayMath.bitXor(self.array, other))
     return r
Exemple #46
0
 def value(self, indices):
     #print type(indices)
     if not isinstance(indices, tuple):
         inds = []
         inds.append(indices)
         indices = inds
     
     if len(indices) != self.ndim:
         print 'indices must be ' + str(self.ndim) + ' dimensions!'
         return None
         
     #origin = []
     #size = []
     #stride = []
     dims = []
     ranges = []
     flips = []
     for i in range(0, self.ndim):  
         k = indices[i]
         if isinstance(indices[i], int):
             sidx = k
             eidx = k
             step = 1                
         elif isinstance(k, slice):
             sidx = 0 if k.start is None else k.start
             eidx = self.dims[i].getLength()-1 if k.stop is None else k.stop
             step = 1 if k.step is None else k.step
         elif isinstance(k, tuple) or isinstance(k, list):
             dim = self.dims[i]
             sidx = dim.getValueIndex(k[0])
             if len(k) == 1:
                 eidx = sidx
                 step = 1
             else:                    
                 eidx = dim.getValueIndex(k[1])
                 if len(k) == 2:
                     step = 1
                 else:
                     step = int(k[2] / dim.getDeltaValue)
         else:
             print k
             return None
             
         if step < 0:
             step = abs(step)
             flips.append(i)
         rr = Range(sidx, eidx, step)
         ranges.append(rr)
         #origin.append(sidx)
         n = eidx - sidx + 1
         #size.append(n)
         #stride.append(step)
         if n > 1:
             dim = self.dims[i]
             dims.append(dim.extract(sidx, eidx, step))
                 
     #r = ArrayMath.section(self.array, origin, size, stride)
     r = ArrayMath.section(self.array, ranges)
     for i in flips:
         r = r.flip(i)
     rr = Array.factory(r.getDataType(), r.getShape());
     MAMath.copy(rr, r);
     array = MIArray(rr)
     data = DimArray(array, dims, self.fill_value, self.proj)
     return data
Exemple #47
0
 def __rshift__(self, other):
     other = MIArray.__value_other(self, other)
     r = MIArray(ArrayMath.rightShift(self.array, other))
     return r
Exemple #48
0
    def __getitem__(self, indices):
        #print type(indices)
        if not isinstance(indices, tuple):
            inds = []
            inds.append(indices)
            indices = inds
            
        allint = True
        aindex = self.array.getIndex()
        i = 0
        for ii in indices:
            if isinstance(ii, int):
                if ii < 0:
                    ii = self.shape[i] + ii
                aindex.setDim(i, ii)
            else:
                allint = False
                break;
            i += 1
        if allint:
            return self.array.getObject(aindex)
        
        if len(indices) != self.ndim:
            print 'indices must be ' + str(self.ndim) + ' dimensions!'
            raise IndexError()
            
        if not self.proj is None and not self.proj.isLonLat():
            xlim = None
            ylim = None
            xidx = -1
            yidx = -1
            for i in range(0, self.ndim):
                dim = self.dims[i]
                if dim.getDimType() == DimensionType.X:                    
                    k = indices[i]
                    #if isinstance(k, (tuple, list)):
                    if isinstance(k, basestring):
                        xlims = k.split(':')
                        xlim = [float(xlims[0]), float(xlims[1])]
                        xidx = i
                elif dim.getDimType() == DimensionType.Y:
                    k = indices[i]
                    #if isinstance(k, (tuple, list)):
                    if isinstance(k, basestring):
                        ylims = k.split(':')
                        ylim = [float(ylims[0]), float(ylims[1])]
                        yidx = i
            if not xlim is None and not ylim is None:                
                fromproj=KnownCoordinateSystems.geographic.world.WGS1984
                inpt = PointD(xlim[0], ylim[0])
                outpt1 = Reproject.reprojectPoint(inpt, fromproj, self.proj)
                inpt = PointD(xlim[1], ylim[1])
                outpt2 = Reproject.reprojectPoint(inpt, fromproj, self.proj)
                xlim = [outpt1.X, outpt2.X]
                ylim = [outpt1.Y, outpt2.Y]
                indices1 = []
                for i in range(0, self.ndim):
                    if i == xidx:
                        #indices1.append(xlim
                        indices1.append(str(xlim[0]) + ':' + str(xlim[1]))
                    elif i == yidx:
                        #indices1.append(ylim)
                        indices1.append(str(ylim[0]) + ':' + str(ylim[1]))
                    else:
                        indices1.append(indices[i])
                indices = indices1

        ndims = []
        ranges = []
        flips = []
        iszerodim = True
        onlyrange = True
        alllist = True
        isempty = False
        nshape = []
        for i in range(0, self.ndim):  
            isrange = True
            k = indices[i]
            if isinstance(k, int):
                if k < 0:
                    k = self.dims[i].getLength() + k
                sidx = k
                eidx = k
                step = 1       
                alllist = False
            elif isinstance(k, slice):
                if isinstance(k.start, basestring):
                    sv = float(k.start)
                    sidx = self.dims[i].getValueIndex(sv)
                elif isinstance(k.start, datetime.datetime):
                    sv = miutil.date2num(k.start)
                    sidx = self.dims[i].getValueIndex(sv)
                else:
                    sidx = 0 if k.start is None else k.start
                if sidx < 0:
                    sidx = self.dims[i].getLength() + sidx
                    
                if isinstance(k.stop, basestring):
                    ev = float(k.stop)
                    eidx = self.dims[i].getValueIndex(ev)
                elif isinstance(k.stop, datetime.datetime):
                    ev = miutil.date2num(k.stop)
                    eidx = self.dims[i].getValueIndex(ev)
                else:
                    eidx = self.dims[i].getLength() if k.stop is None else k.stop
                    if eidx < 0:
                        eidx = self.dims[i].getLength() + eidx
                    eidx -= 1
                    
                if isinstance(k.step, basestring):
                    nv = float(k.step) + self.dims[i].getDimValue()[0]
                    nidx = self.dims[i].getValueIndex(nv)
                    step = nidx - sidx
                elif isinstance(k.step, datetime.timedelta):
                    nv = miutil.date2num(k.start + k.step)
                    nidx = self.dims[i].getValueIndex(nv)
                    step = nidx - sidx
                else:
                    step = 1 if k.step is None else k.step
                alllist = False
            elif isinstance(k, list):
                onlyrange = False
                isrange = False
                if not isinstance(k[0], datetime.datetime):                    
                    ranges.append(k)
                else:
                    tlist = []
                    for tt in k:
                        sv = miutil.date2num(tt)
                        idx = self.dims[i].getValueIndex(sv)
                        tlist.append(idx)
                    ranges.append(tlist)
                    k = tlist
            elif isinstance(k, basestring):
                dim = self.dims[i]
                kvalues = k.split(':')
                sidx = dim.getValueIndex(float(kvalues[0]))
                if len(kvalues) == 1:
                    eidx = sidx
                    step = 1
                else:                    
                    eidx = dim.getValueIndex(float(kvalues[1]))
                    if len(kvalues) == 2:
                        step = 1
                    else:
                        step = int(float(kvalues[2]) / dim.getDeltaValue())
                    if sidx > eidx:
                        iidx = eidx
                        eidx = sidx
                        sidx = iidx
                alllist = False
            else:                
                print k
                raise IndexError()
                
            if isrange:
                if sidx >= self.shape[i]:
                    raise IndexError()
                    
                if sidx != eidx:
                    iszerodim = False
                if step < 0:
                    step = abs(step)
                    flips.append(i)
                    if eidx < sidx:
                        tempidx = sidx
                        sidx = eidx + 2
                        eidx = tempidx
                if eidx < sidx:
                    isempty = True
                else:
                    rr = Range(sidx, eidx, step)
                    ranges.append(rr)
                    n = eidx - sidx + 1
                    if n > 1:
                        dim = self.dims[i]
                        ndims.append(dim.extract(sidx, eidx, step))
                nshape.append(eidx - sidx + 1 if eidx - sidx >= 0 else 0)
            else:
                if len(k) > 1:
                    dim = self.dims[i]
                    ndims.append(dim.extract(k))
        
        if isempty:
            r = ArrayUtil.zeros(nshape, 'int')
            return MIArray(r)
        
        if onlyrange:
            r = ArrayMath.section(self.array, ranges)
        else:
            if alllist:
                r = ArrayMath.takeValues(self.array, ranges)
                return MIArray(r)
            else:
                r = ArrayMath.take(self.array, ranges)
        if r.getSize() == 1:
            return r.getObject(0)
        else:
            for i in flips:
                r = r.flip(i)
            rr = Array.factory(r.getDataType(), r.getShape());
            MAMath.copy(rr, r);
            array = MIArray(rr)
            data = DimArray(array, ndims, self.fill_value, self.proj)
            return data        
Exemple #49
0
 def sqrt(self):
     return MIArray(ArrayMath.sqrt(self.array))
Exemple #50
0
    def __setitem__(self, indices, value):
        #print type(indices)
        if isinstance(indices, MIArray):
            if isinstance(value, MIArray):
                value = value.asarray()
            ArrayMath.setValue(self.array, indices.array, value)
            return None

        if not isinstance(indices, tuple):
            inds = []
            inds.append(indices)
            indices = inds

        if self.ndim == 0:
            self.array.setObject(0, value)
            return None

        if len(indices) != self.ndim:
            print 'indices must be ' + str(self.ndim) + ' dimensions!'
            return None

        ranges = []
        flips = []
        onlyrange = True
        alllist = True
        for i in range(0, self.ndim):
            k = indices[i]
            if isinstance(k, int):
                sidx = k
                if sidx < 0:
                    sidx = self._shape[i] + sidx
                eidx = sidx
                step = 1
                alllist = False
            elif isinstance(k, (list, tuple, MIArray)):
                if isinstance(k, MIArray):
                    k = k.aslist()
                onlyrange = False
                ranges.append(k)
                continue
            else:
                sidx = 0 if k.start is None else k.start
                if sidx < 0:
                    sidx = self._shape[i] + sidx
                eidx = self._shape[i] if k.stop is None else k.stop
                if eidx < 0:
                    eidx = self._shape[i] + eidx
                eidx -= 1
                step = 1 if k.step is None else k.step
                alllist = False
            if step < 0:
                step = abs(step)
                flips.append(i)
            rr = Range(sidx, eidx, step)
            ranges.append(rr)

        if isinstance(value, (list, tuple)):
            value = ArrayUtil.array(value)
        if isinstance(value, MIArray):
            value = value.asarray()
        if onlyrange:
            r = ArrayMath.setSection(self.array, ranges, value)
        else:
            if alllist:
                r = ArrayMath.setSection_List(self.array, ranges, value)
            else:
                r = ArrayMath.setSection_Mix(self.array, ranges, value)
        self.array = r
Exemple #51
0
 def acos(self):
     return MIArray(ArrayMath.acos(self.array))
Exemple #52
0
 def __abs__(self):
     return MIArray(ArrayMath.abs(self.array))
Exemple #53
0
 def exp(self):
     return MIArray(ArrayMath.exp(self.array))
Exemple #54
0
 def __rpow__(self, other):
     other = MIArray.__value_other(self, other)
     r = ArrayMath.pow(other, self.array)
     if r is None:
         raise ValueError('Dimension missmatch, can not broadcast!')
     return MIArray(r)
Exemple #55
0
 def aslist(self):
     r = ArrayMath.asList(self.array)
     return list(r)
Exemple #56
0
 def __neg__(self):
     r = MIArray(ArrayMath.sub(0, self.array))
     return r
Exemple #57
0
    def __getitem__(self, indices):
        #print type(indices)
        if not isinstance(indices, tuple):
            inds = []
            inds.append(indices)
            indices = inds

        allint = True
        aindex = self.array.getIndex()
        i = 0
        for ii in indices:
            if isinstance(ii, int):
                if ii < 0:
                    ii = self.shape[i] + ii
                aindex.setDim(i, ii)
            else:
                allint = False
                break
            i += 1
        if allint:
            return self.array.getObject(aindex)

        if self.ndim == 0:
            return self

        if len(indices) != self.ndim:
            print 'indices must be ' + str(self.ndim) + ' dimensions!'
            raise IndexError()

        ranges = []
        flips = []
        onlyrange = True
        alllist = True
        isempty = False
        nshape = []
        for i in range(0, self.ndim):
            k = indices[i]
            if isinstance(k, int):
                if k < 0:
                    k = self._shape[i] + k
                sidx = k
                eidx = k
                step = 1
                alllist = False
            elif isinstance(k, slice):
                sidx = 0 if k.start is None else k.start
                if sidx < 0:
                    sidx = self._shape[i] + sidx
                eidx = self._shape[i] if k.stop is None else k.stop
                if eidx < 0:
                    eidx = self._shape[i] + eidx
                eidx -= 1
                step = 1 if k.step is None else k.step
                alllist = False
            elif isinstance(k, (list, tuple, MIArray)):
                if isinstance(k, MIArray):
                    k = k.aslist()
                if isinstance(k[0], bool):
                    kk = []
                    for i in range(len(k)):
                        if k[i]:
                            kk.append(i)
                    k = kk
                onlyrange = False
                ranges.append(k)
                continue
            else:
                print k
                return None
            if step < 0:
                step = abs(step)
                flips.append(i)
                if eidx < sidx:
                    tempidx = sidx
                    sidx = eidx + 2
                    eidx = tempidx
            if sidx >= self.shape[i]:
                raise IndexError()
            if eidx < sidx:
                isempty = True
            else:
                rr = Range(sidx, eidx, step)
                ranges.append(rr)
            nshape.append(eidx - sidx + 1 if eidx - sidx >= 0 else 0)

        if isempty:
            r = ArrayUtil.zeros(nshape, 'int')
            return MIArray(r)

        if onlyrange:
            r = ArrayMath.section(self.array, ranges)
        else:
            if alllist:
                r = ArrayMath.takeValues(self.array, ranges)
            else:
                r = ArrayMath.take(self.array, ranges)
        if r.getSize() == 1:
            r = r.getObject(0)
            if isinstance(r, Complex):
                return complex(r.getReal(), r.getImaginary())
            else:
                return r
        else:
            for i in flips:
                r = r.flip(i)
            rr = Array.factory(r.getDataType(), r.getShape())
            MAMath.copy(rr, r)
            return MIArray(rr)
Exemple #58
0
 def __le__(self, other):
     other = MIArray.__value_other(self, other)
     r = MIArray(ArrayMath.lessThanOrEqual(self.array, other))
     return r
Exemple #59
0
 def __getitem__(self, indices):
     if isinstance(indices, slice):
         k = indices
         if k.start is None and k.stop is None and k.step is None:
             r = self.dataset.dataset.read(self.name)
             return DimArray(r, self.dims, self.fill_value, self.proj)
         
     if isinstance(indices, tuple):
         allnone = True
         for k in indices:
             if isinstance(k, slice):
                 if (not k.start is None) or (not k.stop is None) or (not k.step is None):
                     allnone = False
                     break
             else:
                 allnone = False
                 break
         if allnone:
             r = self.dataset.dataset.read(self.name)
             return DimArray(r, self.dims, self.fill_value, self.proj)
         
     if indices is None:
         inds = []
         for i in range(self.ndim):
             inds.append(slice(None))
         indices = tuple(inds)
             
     if isinstance(indices, str):    #metadata
         rr = self.dataset.read(self.name)
         m = rr.findMember(indices)
         data = rr.getArray(0, m)
         return NDArray(data)
     
     if not isinstance(indices, tuple):
         inds = []
         inds.append(indices)
         indices = inds
     
     if len(indices) != self.ndim:
         print 'indices must be ' + str(self.ndim) + ' dimensions!'
         return None
         
     if not self.proj is None and not self.proj.isLonLat():
         xlim = None
         ylim = None
         xidx = -1
         yidx = -1
         for i in range(0, self.ndim):
             dim = self.dims[i]
             if dim.getDimType() == DimensionType.X:                    
                 k = indices[i]
                 if isinstance(k, basestring):
                     xlims = k.split(':')
                     if len(xlims) == 1:
                         xlim = [float(xlims[0])]
                     else:
                         xlim = [float(xlims[0]), float(xlims[1])]
                     xidx = i
             elif dim.getDimType() == DimensionType.Y:
                 k = indices[i]
                 if isinstance(k, basestring):
                     ylims = k.split(':')
                     if len(ylims) == 1:
                         ylim = [float(ylims[0])]
                     else:
                         ylim = [float(ylims[0]), float(ylims[1])]
                     yidx = i
         if not xlim is None and not ylim is None:                
             fromproj=KnownCoordinateSystems.geographic.world.WGS1984
             inpt = PointD(xlim[0], ylim[0])
             outpt1 = Reproject.reprojectPoint(inpt, fromproj, self.proj)
             if len(xlim) == 1:
                 xlim = [outpt1.X]
                 ylim = [outpt1.Y]
             else:
                 inpt = PointD(xlim[1], ylim[1])
                 outpt2 = Reproject.reprojectPoint(inpt, fromproj, self.proj)
                 xlim = [outpt1.X, outpt2.X]
                 ylim = [outpt1.Y, outpt2.Y]
             indices1 = []
             for i in range(0, self.ndim):
                 if i == xidx:
                     if len(xlim) == 1:
                         indices1.append(str(xlim[0]))
                     else:
                         indices1.append(str(xlim[0]) + ':' + str(xlim[1]))
                 elif i == yidx:
                     if len(ylim) == 1:
                         indices1.append(str(ylim[0]))
                     else:
                         indices1.append(str(ylim[0]) + ':' + str(ylim[1]))
                 else:
                     indices1.append(indices[i])
             indices = indices1
     
     origin = []
     size = []
     stride = []
     ranges = []
     dims = []
     flips = []
     onlyrange = True
     for i in range(0, self.ndim):  
         isrange = True
         dimlen = self.dimlen(i)
         k = indices[i]
         if isinstance(k, int):
             if k < 0:
                 k = self.dims[i].getLength() + k
             sidx = k
             eidx = k
             step = 1
         elif isinstance(k, slice):
             if isinstance(k.start, basestring):
                 sv = float(k.start)
                 sidx = self.dims[i].getValueIndex(sv)
             elif isinstance(k.start, datetime.datetime):
                 sv = miutil.date2num(k.start)
                 sidx = self.dims[i].getValueIndex(sv)
             else:
                 sidx = 0 if k.start is None else k.start
             if sidx < 0:
                 sidx = self.dimlen(i) + sidx
                 
             if isinstance(k.stop, basestring):
                 ev = float(k.stop)
                 eidx = self.dims[i].getValueIndex(ev)
             elif isinstance(k.stop, datetime.datetime):
                 ev = miutil.date2num(k.stop)
                 eidx = self.dims[i].getValueIndex(ev)
             else:
                 eidx = self.dimlen(i) if k.stop is None else k.stop
                 if eidx < 0:
                     eidx = self.dimlen(i) + eidx
                 eidx -= 1
                 
             if isinstance(k.step, basestring):
                 nv = float(k.step) + self.dims[i].getDimValue()[0]
                 nidx = self.dims[i].getValueIndex(nv)
                 step = nidx - sidx
             elif isinstance(k.step, datetime.timedelta):
                 nv = miutil.date2num(k.start + k.step)
                 nidx = self.dims[i].getValueIndex(nv)
                 step = nidx - sidx
             else:
                 step = 1 if k.step is None else k.step
             if sidx > eidx:
                 iidx = eidx
                 eidx = sidx
                 sidx = iidx
         elif isinstance(k, list):
             onlyrange = False
             isrange = False
             if not isinstance(k[0], datetime.datetime):
                 ranges.append(k)
             else:
                 tlist = []
                 for tt in k:
                     sv = miutil.date2num(tt)
                     idx = self.dims[i].getValueIndex(sv)
                     tlist.append(idx)
                 ranges.append(tlist)
                 k = tlist
         elif isinstance(k, basestring):
             dim = self.variable.getDimension(i)
             kvalues = k.split(':')
             sv = float(kvalues[0])
             sidx = dim.getValueIndex(sv)
             if len(kvalues) == 1:
                 eidx = sidx
                 step = 1
             else:                    
                 ev = float(kvalues[1])
                 eidx = dim.getValueIndex(ev)
                 if len(kvalues) == 2:
                     step = 1
                 else:
                     step = int(float(kvalues[2]) / dim.getDeltaValue())
                 if sidx > eidx:
                     iidx = eidx
                     eidx = sidx
                     sidx = iidx
         else:
             print k
             return None
         if isrange:
             if eidx >= dimlen:
                 print 'Index out of range!'
                 return None
             origin.append(sidx)
             n = eidx - sidx + 1
             size.append(n)                   
             if n > 1:
                 dim = self.variable.getDimension(i)
                 if dim.isReverse():
                     step = -step      
                 dim = dim.extract(sidx, eidx, step)
                 dim.setReverse(False)
                 dims.append(dim)
             stride.append(step) 
             if step < 0:
                 step = abs(step)
                 flips.append(i)
             rr = Range(sidx, eidx, step)
             ranges.append(rr)
         else:
             if len(k) > 1:
                 dim = self.variable.getDimension(i)
                 dim = dim.extract(k)
                 dim.setReverse(False)
                 dims.append(dim)
     #rr = self.dataset.read(self.name, origin, size, stride).reduce()
     if onlyrange:
         rr = self.dataset.dataset.read(self.name, ranges)
     else:
         rr = self.dataset.dataset.take(self.name, ranges)
     if rr.getSize() == 1:
         return rr.getObject(0)
     else:
         for i in flips:
             rr = rr.flip(i)
         rr = rr.reduce()
         ArrayMath.missingToNaN(rr, self.fill_value)
         if len(flips) > 0:
             rrr = Array.factory(rr.getDataType(), rr.getShape())
             MAMath.copy(rrr, rr)
             array = NDArray(rrr)
         else:
             array = NDArray(rr)
         data = DimArray(array, dims, self.fill_value, self.dataset.proj)
         return data
Exemple #60
0
 def exp(self):
     return MIArray(ArrayMath.exp(self.array))