add mgrid function

This commit is contained in:
wyq 2023-06-13 22:51:05 +08:00
parent 9cee1ed5ee
commit 223b8fd231
8 changed files with 217 additions and 17 deletions

View File

@ -1,21 +1,21 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<MeteoInfo File="milconfig.xml" Type="configurefile">
<Path OpenPath="D:\Working\MIScript\Jython\mis\plot_types\funny">
<RecentFolder Folder="D:\Working\MIScript\Jython\mis\map"/>
<Path OpenPath="D:\Working\MIScript\Jython\mis\plot_types\3d\jogl\surf">
<RecentFolder Folder="D:\Working\MIScript\Jython\mis\io\dataconvert"/>
<RecentFolder Folder="D:\Working\MIScript\Jython\mis\io"/>
<RecentFolder Folder="D:\Working\MIScript\Jython\mis\io\burf"/>
<RecentFolder Folder="D:\Working\MIScript\Jython\mis"/>
<RecentFolder Folder="D:\Working\MIScript\Jython\mis\LaSW"/>
<RecentFolder Folder="D:\Working\MIScript\Jython\mis\LaSW\ZhengZhou"/>
<RecentFolder Folder="D:\Working\MIScript\Jython\mis\plot_types\contour"/>
<RecentFolder Folder="D:\Working\MIScript\Jython\mis\plot_types\3d"/>
<RecentFolder Folder="D:\Working\MIScript\Jython\mis\plot_types\3d\jogl\surf"/>
<RecentFolder Folder="D:\Working\MIScript\Jython\mis\plot_types\3d\jogl\slice"/>
<RecentFolder Folder="D:\Working\MIScript\Jython\mis\plot_types\3d\jogl"/>
<RecentFolder Folder="D:\Working\MIScript\Jython\mis\plot_types\3d\jogl\contour"/>
<RecentFolder Folder="D:\Working\MIScript\Jython\mis\plot_types"/>
<RecentFolder Folder="D:\Working\MIScript\Jython\mis\plot_types\funny"/>
<RecentFolder Folder="D:\Working\MIScript\Jython\mis"/>
<RecentFolder Folder="D:\Working\MIScript\Jython\mis\array"/>
<RecentFolder Folder="D:\Working\MIScript\Jython\mis\plot_types"/>
<RecentFolder Folder="D:\Working\MIScript\Jython\mis\plot_types\3d"/>
<RecentFolder Folder="D:\Working\MIScript\Jython\mis\plot_types\3d\jogl"/>
<RecentFolder Folder="D:\Working\MIScript\Jython\mis\plot_types\3d\jogl\surf"/>
</Path>
<File>
<OpenedFiles>
@ -23,12 +23,14 @@
<OpenedFile File="D:\MyProgram\java\MeteoInfoDev\toolbox\meteoview3d\mainGUI.py"/>
<OpenedFile File="D:\Working\MIScript\Jython\mis\plot_types\3d\jogl\slice\slice_2d.py"/>
<OpenedFile File="D:\Working\MIScript\Jython\mis\plot_types\funny\butterfly.py"/>
<OpenedFile File="D:\Working\MIScript\Jython\mis\array\mgrid_1.py"/>
</OpenedFiles>
<RecentFiles>
<RecentFile File="D:\MyProgram\java\MeteoInfoDev\toolbox\meteoview3d\_reload.py"/>
<RecentFile File="D:\MyProgram\java\MeteoInfoDev\toolbox\meteoview3d\mainGUI.py"/>
<RecentFile File="D:\Working\MIScript\Jython\mis\plot_types\3d\jogl\slice\slice_2d.py"/>
<RecentFile File="D:\Working\MIScript\Jython\mis\plot_types\funny\butterfly.py"/>
<RecentFile File="D:\Working\MIScript\Jython\mis\array\mgrid_1.py"/>
</RecentFiles>
</File>
<Font>
@ -36,5 +38,5 @@
</Font>
<LookFeel DockWindowDecorated="true" LafDecorated="true" Name="FlatDarkLaf"/>
<Figure DoubleBuffering="true"/>
<Startup MainFormLocation="-7,0" MainFormSize="1419,836"/>
<Startup MainFormLocation="-7,-7" MainFormSize="1293,685"/>
</MeteoInfo>

View File

@ -279,7 +279,7 @@ class NDArray(object):
return None
if len(indices) != self.ndim:
print 'indices must be ' + str(self.ndim) + ' dimensions!'
print('indices must be ' + str(self.ndim) + ' dimensions!')
raise IndexError()
ranges = []

View File

@ -42,7 +42,7 @@ __all__ = [
'arctan2','atan2','ave_month','average','histogram','broadcast_to','cdiff','ceil',
'concatenate','conj','conjugate','corrcoef','cos','cosh','cylinder','degrees','delete','delnan','diag','diff',
'datatable','dot','empty','empty_like','exp','eye','flatnonzero','floor',
'fmax','fmin','full','hcurl','hdivg','hstack','identity','interp2d','interpn','isarray',
'fmax','fmin','full','hcurl','hdivg','hstack','identity','indices','interp2d','interpn','isarray',
'isclose','isfinite','isinf','isnan','isscalar','linspace','log','log10','logical_not','logspace',
'magnitude','max','maximum','mean','median','meshgrid','min','minimum','monthname',
'moveaxis','newaxis','ones','ones_like','outer','peaks','pol2cart','power','radians','reciprocal','reshape',
@ -1715,6 +1715,83 @@ def argsort(a, axis=-1):
r = ArrayUtil.argSort(a.asarray(), axis)
return NDArray(r)
def indices(dimensions, dtype='int'):
"""
Return an array representing the indices of a grid.
Compute an array where the subarrays contain index values 0, 1, ...
varying only along the corresponding axis.
Parameters
----------
dimensions : sequence of ints
The shape of the grid.
dtype : dtype, optional
Data type of the result.
Returns
-------
grid : one ndarray or tuple of ndarrays
If sparse is False:
Returns one array of grid indices,
``grid.shape = (len(dimensions),) + tuple(dimensions)``.
If sparse is True:
Returns a tuple of arrays, with
``grid[i].shape = (1, ..., 1, dimensions[i], 1, ..., 1)`` with
dimensions[i] in the ith place
See Also
--------
mgrid, ogrid, meshgrid
Notes
-----
The output shape in the dense case is obtained by prepending the number
of dimensions in front of the tuple of dimensions, i.e. if `dimensions`
is a tuple ``(r0, ..., rN-1)`` of length ``N``, the output shape is
``(N, r0, ..., rN-1)``.
The subarrays ``grid[k]`` contains the N-D array of indices along the
``k-th`` axis. Explicitly::
grid[k, i0, i1, ..., iN-1] = ik
Examples
--------
>>> grid = np.indices((2, 3))
>>> grid.shape
(2, 2, 3)
>>> grid[0] # row indices
array([[0, 0, 0],
[1, 1, 1]])
>>> grid[1] # column indices
array([[0, 1, 2],
[0, 1, 2]])
The indices can be used as an index into an array.
>>> x = np.arange(20).reshape(5, 4)
>>> row, col = np.indices((2, 3))
>>> x[row, col]
array([[0, 1, 2],
[4, 5, 6]])
Note that it would be more straightforward in the above example to
extract the required elements directly with ``x[:2, :3]``.
"""
dimensions = tuple(dimensions)
N = len(dimensions)
shape = (1,)*N
res = empty((N,)+dimensions, dtype=dtype)
for i, dim in enumerate(dimensions):
idx = arange(dim, dtype=dtype).reshape(
shape[:i] + (dim,) + shape[i+1:]
)
res[i] = idx
return res
def isnan(a):
"""
Test element-wise for NaN and return result as a boolean array.
@ -2235,7 +2312,7 @@ def meshgrid(*args):
if isinstance(x, list):
x = array(x)
if x.ndim != 1:
print 'The paramters must be vector arrays!'
print('The parameters must be vector arrays!')
return None
xs.append(x._array)

View File

@ -1,7 +1,129 @@
import math
from mipylib.numeric import core as _nx
from ..core.numerictypes import ScalarType, find_common_type
__all__ = ['r_','c_']
__all__ = ['r_','c_','mgrid']
class nd_grid(object):
"""
Construct a multi-dimensional "meshgrid".
``grid = nd_grid()`` creates an instance which will return a mesh-grid
when indexed. The dimension and number of the output arrays are equal
to the number of indexing dimensions. If the step length is not a
complex number, then the stop is not inclusive.
However, if the step length is a **complex number** (e.g. 5j), then the
integer part of its magnitude is interpreted as specifying the
number of points to create between the start and stop values, where
the stop value **is inclusive**.
If instantiated with an argument of ``sparse=True``, the mesh-grid is
open (or not fleshed out) so that only one-dimension of each returned
argument is greater than 1.
Parameters
----------
sparse : bool, optional
Whether the grid is sparse or not. Default is False.
Notes
-----
The instances of `nd_grid`, `mgrid`, approximately defined as::
mgrid = nd_grid(sparse=False)
Users should use these pre-defined instances instead of using `nd_grid`
directly.
"""
def __init__(self, sparse=False):
self.sparse = sparse
def __getitem__(self, key):
try:
num_list = []
for k in range(len(key)):
step = key[k].step
start = key[k].start
stop = key[k].stop
if start is None:
start = 0
if step is None:
step = 1
if isinstance(step, complex):
step = abs(step)
length = int(step)
num_list.insert(0, _nx.linspace(start, stop, length))
else:
num_list.insert(0, _nx.arange(start, stop, step))
nn = _nx.meshgrid(*num_list)
return nn[::-1]
except (IndexError, TypeError):
step = key.step
stop = key.stop
start = key.start
if start is None:
start = 0
if isinstance(step, complex):
# Prevent the (potential) creation of integer arrays
step_float = abs(step)
length = int(step_float)
return _nx.linspace(start, stop, length)
else:
return _nx.arange(start, stop, step)
class MGridClass(nd_grid):
"""
An instance which returns a dense multi-dimensional "meshgrid".
An instance which returns a dense (or fleshed out) mesh-grid
when indexed, so that each returned argument has the same shape.
The dimensions and number of the output arrays are equal to the
number of indexing dimensions. If the step length is not a complex
number, then the stop is not inclusive.
However, if the step length is a **complex number** (e.g. 5j), then
the integer part of its magnitude is interpreted as specifying the
number of points to create between the start and stop values, where
the stop value **is inclusive**.
Returns
-------
mesh-grid `ndarrays` all of the same dimensions
See Also
--------
ogrid : like `mgrid` but returns open (not fleshed out) mesh grids
meshgrid: return coordinate matrices from coordinate vectors
r_ : array concatenator
:ref:`how-to-partition`
Examples
--------
>>> np.mgrid[0:5, 0:5]
array([[[0, 0, 0, 0, 0],
[1, 1, 1, 1, 1],
[2, 2, 2, 2, 2],
[3, 3, 3, 3, 3],
[4, 4, 4, 4, 4]],
[[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]]])
>>> np.mgrid[-1:1:5j]
array([-1. , -0.5, 0. , 0.5, 1. ])
"""
def __init__(self):
super(MGridClass, self).__init__(sparse=False)
mgrid = MGridClass()
class AxisConcatenator:
"""

View File

@ -6022,13 +6022,12 @@ public class ArrayMath {
public static Array setSection(Array a, List<Range> ranges, Array v) throws InvalidRangeException {
Array r = a.section(ranges);
IndexIterator iter = r.getIndexIterator();
//int[] current;
if (r.getShape() != v.getShape()) {
v = ArrayUtil.broadcast(v, r.getShape());
}
Index index = v.getIndex();
while (iter.hasNext()) {
iter.next();
//current = iter.getCurrentCounter();
//index.set(current);
iter.setObjectCurrent(v.getObject(index));
iter.setObjectNext(v.getObject(index));
index.incr();
}
r = Array.factory(a.getDataType(), a.getShape(), r.getStorage());