Python numpy.ma.expand_dims() Examples
The following are 8
code examples of numpy.ma.expand_dims().
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.ma
, or try the search function
.
Example #1
Source File: mstats_basic.py From Computable with MIT License | 6 votes |
def moment(a, moment=1, axis=0): a, axis = _chk_asarray(a, axis) if moment == 1: # By definition the first moment about the mean is 0. shape = list(a.shape) del shape[axis] if shape: # return an actual array of the appropriate shape return np.zeros(shape, dtype=float) else: # the input was 1D, so return a scalar instead of a rank-0 array return np.float64(0.0) else: mn = ma.expand_dims(a.mean(axis=axis), axis) s = ma.power((a-mn), moment) return s.mean(axis=axis)
Example #2
Source File: gtiff.py From mapchete with MIT License | 6 votes |
def read(self, indexes=None, **kwargs): """ Read reprojected & resampled input data. Parameters ---------- indexes : integer or list band number or list of band numbers Returns ------- data : array """ band_indexes = self._get_band_indexes(indexes) arr = self.process.get_raw_output(self.tile) return ( arr[band_indexes[0] - 1] if len(band_indexes) == 1 else ma.concatenate([ma.expand_dims(arr[i - 1], 0) for i in band_indexes]) )
Example #3
Source File: UncertMath.py From westpa with MIT License | 5 votes |
def concatenate(self,value,axis=0): """ Concatentate UncertContainer value to self. Assumes that if dimensions of self and value do not match, to add a np.newaxis along axis of value """ if isinstance(value,UncertContainer): if value.vals.ndim == self.vals.ndim: vals = value.vals dmin = value.dmin dmax = value.dmax wt = value.wt uncert = value.uncert mask = value.mask elif (value.vals.ndim + 1) == self.vals.ndim: vals = ma.expand_dims(value.vals,axis) dmin = ma.expand_dims(value.dmin,axis) dmax = ma.expand_dims(value.dmax,axis) wt = ma.expand_dims(value.wt,axis) uncert = ma.expand_dims(value.uncert,axis) mask = np.expand_dims(value.mask,axis) else: raise ValueError('Could not propery match dimensionality') self.vals = ma.concatenate((self.vals,vals),axis=axis) self.dmin = ma.concatenate((self.dmin,dmin),axis=axis) self.dmax = ma.concatenate((self.dmax,dmax),axis=axis) self.wt = ma.concatenate((self.wt,wt),axis=axis) self.uncert = ma.concatenate((self.uncert,uncert),axis=axis) self.mask = np.concatenate((self.mask,mask),axis=axis) else: raise ValueError('Can only concatenate with an UncertContainer object')
Example #4
Source File: UncertMath.py From westpa with MIT License | 4 votes |
def weighted_average(self,axis=0,expaxis=None): """ Calculate weighted average of data along axis after optionally inserting a new dimension into the shape array at position expaxis """ if expaxis is not None: vals = ma.expand_dims(self.vals,expaxis) dmin = ma.expand_dims(self.dmin,expaxis) dmax = ma.expand_dims(self.dmax,expaxis) wt = ma.expand_dims(self.wt,expaxis) else: vals = self.vals wt = self.wt dmin = self.dmin dmax = self.dmax # Get average value avg,norm = ma.average(vals,axis=axis,weights=wt,returned=True) avg_ex = ma.expand_dims(avg,0) # Calculate weighted uncertainty wtmax = ma.max(wt,axis=axis) neff = norm/wtmax # Effective number of samples based on uncertainties # Seeking max deviation from the average; if above avg use max, if below use min term = np.empty_like(vals) indices = np.where(vals > avg_ex) i0 = indices[0] irest = indices[1:] ii = tuple(x for x in itertools.chain([i0],irest)) jj = tuple(x for x in itertools.chain([np.zeros_like(i0)],irest)) term[ii] = (dmax[ii] - avg_ex[jj])**2 indices = np.where(vals <= avg_ex) i0 = indices[0] irest = indices[1:] ii = tuple(x for x in itertools.chain([i0],irest)) jj = tuple(x for x in itertools.chain([np.zeros_like(i0)],irest)) term[ii] = (avg_ex[jj] - dmin[ii])**2 dsum = ma.sum(term*wt,axis=0) # Sum for weighted average of deviations dev = 0.5*np.sqrt(dsum/(norm*neff)) if isinstance(avg,(float,np.float)): avg = avg_ex tmp_min = avg - dev ii = np.where(tmp_min < 0) tmp_min[ii] = TOL*avg[ii] return UncertContainer(avg,tmp_min,avg+dev)
Example #5
Source File: mstats_basic.py From lambda-packs with MIT License | 4 votes |
def moment(a, moment=1, axis=0): """ Calculates the nth moment about the mean for a sample. Parameters ---------- a : array_like data moment : int, optional order of central moment that is returned axis : int or None, optional Axis along which the central moment is computed. Default is 0. If None, compute over the whole array `a`. Returns ------- n-th central moment : ndarray or float The appropriate moment along the given axis or over all values if axis is None. The denominator for the moment calculation is the number of observations, no degrees of freedom correction is done. Notes ----- For more details about `moment`, see `stats.moment`. """ a, axis = _chk_asarray(a, axis) if moment == 1: # By definition the first moment about the mean is 0. shape = list(a.shape) del shape[axis] if shape: # return an actual array of the appropriate shape return np.zeros(shape, dtype=float) else: # the input was 1D, so return a scalar instead of a rank-0 array return np.float64(0.0) else: # Exponentiation by squares: form exponent sequence n_list = [moment] current_n = moment while current_n > 2: if current_n % 2: current_n = (current_n-1)/2 else: current_n /= 2 n_list.append(current_n) # Starting point for exponentiation by squares a_zero_mean = a - ma.expand_dims(a.mean(axis), axis) if n_list[-1] == 1: s = a_zero_mean.copy() else: s = a_zero_mean**2 # Perform multiplications for n in n_list[-2::-1]: s = s**2 if n % 2: s *= a_zero_mean return s.mean(axis)
Example #6
Source File: mstats_basic.py From GraphicDesignPatternByPython with MIT License | 4 votes |
def moment(a, moment=1, axis=0): """ Calculates the nth moment about the mean for a sample. Parameters ---------- a : array_like data moment : int, optional order of central moment that is returned axis : int or None, optional Axis along which the central moment is computed. Default is 0. If None, compute over the whole array `a`. Returns ------- n-th central moment : ndarray or float The appropriate moment along the given axis or over all values if axis is None. The denominator for the moment calculation is the number of observations, no degrees of freedom correction is done. Notes ----- For more details about `moment`, see `stats.moment`. """ a, axis = _chk_asarray(a, axis) if moment == 1: # By definition the first moment about the mean is 0. shape = list(a.shape) del shape[axis] if shape: # return an actual array of the appropriate shape return np.zeros(shape, dtype=float) else: # the input was 1D, so return a scalar instead of a rank-0 array return np.float64(0.0) else: # Exponentiation by squares: form exponent sequence n_list = [moment] current_n = moment while current_n > 2: if current_n % 2: current_n = (current_n-1)/2 else: current_n /= 2 n_list.append(current_n) # Starting point for exponentiation by squares a_zero_mean = a - ma.expand_dims(a.mean(axis), axis) if n_list[-1] == 1: s = a_zero_mean.copy() else: s = a_zero_mean**2 # Perform multiplications for n in n_list[-2::-1]: s = s**2 if n % 2: s *= a_zero_mean return s.mean(axis)
Example #7
Source File: mstats_basic.py From Splunking-Crime with GNU Affero General Public License v3.0 | 4 votes |
def moment(a, moment=1, axis=0): """ Calculates the nth moment about the mean for a sample. Parameters ---------- a : array_like data moment : int, optional order of central moment that is returned axis : int or None, optional Axis along which the central moment is computed. Default is 0. If None, compute over the whole array `a`. Returns ------- n-th central moment : ndarray or float The appropriate moment along the given axis or over all values if axis is None. The denominator for the moment calculation is the number of observations, no degrees of freedom correction is done. Notes ----- For more details about `moment`, see `stats.moment`. """ a, axis = _chk_asarray(a, axis) if moment == 1: # By definition the first moment about the mean is 0. shape = list(a.shape) del shape[axis] if shape: # return an actual array of the appropriate shape return np.zeros(shape, dtype=float) else: # the input was 1D, so return a scalar instead of a rank-0 array return np.float64(0.0) else: # Exponentiation by squares: form exponent sequence n_list = [moment] current_n = moment while current_n > 2: if current_n % 2: current_n = (current_n-1)/2 else: current_n /= 2 n_list.append(current_n) # Starting point for exponentiation by squares a_zero_mean = a - ma.expand_dims(a.mean(axis), axis) if n_list[-1] == 1: s = a_zero_mean.copy() else: s = a_zero_mean**2 # Perform multiplications for n in n_list[-2::-1]: s = s**2 if n % 2: s *= a_zero_mean return s.mean(axis)
Example #8
Source File: raster.py From mapchete with MIT License | 4 votes |
def prepare_array(data, masked=True, nodata=0, dtype="int16"): """ Turn input data into a proper array for further usage. Output array is always 3-dimensional with the given data type. If the output is masked, the fill_value corresponds to the given nodata value and the nodata value will be burned into the data array. Parameters ---------- data : array or iterable array (masked or normal) or iterable containing arrays nodata : integer or float nodata value (default: 0) used if input is not a masked array and for output array masked : bool return a NumPy Array or a NumPy MaskedArray (default: True) dtype : string data type of output array (default: "int16") Returns ------- array : array """ # input is iterable if isinstance(data, (list, tuple)): return _prepare_iterable(data, masked, nodata, dtype) # special case if a 2D single band is provided elif isinstance(data, np.ndarray) and data.ndim == 2: data = ma.expand_dims(data, axis=0) # input is a masked array if isinstance(data, ma.MaskedArray): return _prepare_masked(data, masked, nodata, dtype) # input is a NumPy array elif isinstance(data, np.ndarray): if masked: return ma.masked_values(data.astype(dtype, copy=False), nodata, copy=False) else: return data.astype(dtype, copy=False) else: raise ValueError( "Data must be array, masked array or iterable containing arrays. " "Current data: %s (%s)" % (data, type(data)) )