add polygonindex function

This commit is contained in:
wyq 2023-02-14 15:28:24 +08:00
parent 7fac130689
commit 16a9d12261
13 changed files with 315 additions and 130 deletions

View File

@ -67,7 +67,7 @@ import java.util.zip.ZipInputStream;
public static String getVersion(){
String version = GlobalUtil.class.getPackage().getImplementationVersion();
if (version == null || version.equals("")) {
version = "3.5.5";
version = "3.5.6";
}
return version;
}

View File

@ -1183,7 +1183,7 @@ public class VectorLayer extends MapLayer {
aField.setColumnName(aField.getColumnName() + "_1");
}
}
_attributeTable.getTable().getColumns().add(aField);
_attributeTable.getTable().addColumn(aField);
}
/**

View File

@ -243,6 +243,28 @@ public class GeoComputation {
return isIn;
}
/**
* Get polygon index from polygons by a point
* @param polygons The polygons
* @param point The point
* @return Polygon index - the point is inside the polygon
*/
public static int polygonIndex(List<PolygonShape> polygons, PointD point) {
int idx = -1;
Extent ext = GeometryUtil.getExtent(polygons);
if (MIMath.pointInExtent(point, ext)) {
PolygonShape polygonShape;
for (int i = 0; i < polygons.size(); i++) {
polygonShape = polygons.get(i);
if (pointInPolygon(polygonShape, point)) {
return i;
}
}
}
return idx;
}
// /**
// * Determine if a point loacted in a polygon layer
// *

View File

@ -446,21 +446,28 @@ public class GeometryUtil {
return inPolygon(x, y, shapes);
}
// /**
// * Maskout function
// *
// * @param a Array a
// * @param x X dimension values
// * @param y Y dimension values
// * @param layer VectorLayer
// * @param missingValue Missing value
// * @return Result array with cell values of missing outside polygons
// */
// public static Array maskout(Array a, List<Number> x, List<Number> y, VectorLayer layer, Number missingValue) {
// List<PolygonShape> polygons = (List<PolygonShape>) layer.getShapes();
// return maskout(a, x, y, polygons, missingValue);
// }
/**
* Find polygon index for each point
* @param x X coordinate of the points
* @param y Y coordinate of the points
* @param polygons The polygons
* @return Polygon index for each point
*/
public static Array polygonIndex(Array x, Array y, List<PolygonShape> polygons) {
Array r = Array.factory(DataType.INT, x.getShape());
IndexIterator xIter = x.getIndexIterator();
IndexIterator yIter = y.getIndexIterator();
IndexIterator rIter = r.getIndexIterator();
int idx;
while (rIter.hasNext()){
idx = GeoComputation.polygonIndex(polygons, new PointD(xIter.getDoubleNext(),
yIter.getDoubleNext()));
rIter.setIntNext(idx);
}
return r;
}
/**
* Maskout function

View File

@ -1,14 +1,7 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<MeteoInfo File="milconfig.xml" Type="configurefile">
<Path OpenPath="D:\Working\MIScript\Jython\mis\plot_types\3d\jogl\bar">
<RecentFolder Folder="D:\Working\MIScript\Jython\mis\io\radar"/>
<RecentFolder Folder="D:\Working\MIScript\Jython\mis\plot_types\3d\jogl\scatter"/>
<RecentFolder Folder="D:\Working\MIScript\Jython\mis\plot_types\3d\jogl\quiver"/>
<RecentFolder Folder="D:\Working\MIScript\Jython\mis\plot_types\3d\jogl\surf"/>
<RecentFolder Folder="D:\Working\MIScript\Jython\mis\common_math\interpolate"/>
<RecentFolder Folder="D:\Working\MIScript\Jython\mis\plot_types\3d\jogl\isosurface"/>
<Path OpenPath="D:\Working\MIScript\Jython\mis\dataframe">
<RecentFolder Folder="D:\Working\MIScript\Jython\mis\plot_types\3d\jogl\particles"/>
<RecentFolder Folder="D:\Working\MIScript\Jython\mis"/>
<RecentFolder Folder="D:\Working\MIScript\Jython\mis\plot_types"/>
<RecentFolder Folder="D:\Working\MIScript\Jython\mis\plot_types\wind"/>
<RecentFolder Folder="D:\Working\MIScript\Jython\mis\plot_types\3d\3d_earth"/>
@ -16,19 +9,24 @@
<RecentFolder Folder="D:\Working\MIScript\Jython\mis\plot_types\3d\jogl\contour"/>
<RecentFolder Folder="D:\Working\MIScript\Jython\mis\common_math"/>
<RecentFolder Folder="D:\Working\MIScript\Jython\mis\plot_types\3d\jogl\bar"/>
<RecentFolder Folder="D:\Working\MIScript\Jython\mis\map\geod"/>
<RecentFolder Folder="D:\Working\MIScript\Jython\mis\map\geoshow"/>
<RecentFolder Folder="D:\Working\MIScript\Jython\mis"/>
<RecentFolder Folder="D:\Working\MIScript\Jython\mis\map\topology"/>
<RecentFolder Folder="D:\Working\MIScript\Jython\mis\map"/>
<RecentFolder Folder="D:\Working\MIScript\Jython\mis\map\maskout"/>
<RecentFolder Folder="D:\Working\MIScript\Jython\mis\dataframe"/>
</Path>
<File>
<OpenedFiles>
<OpenedFile File="D:\Working\MIScript\Jython\mis\plot_types\3d\jogl\surf\surf_pumpkin_1.py"/>
<OpenedFile File="D:\Working\MIScript\Jython\mis\plot_types\3d\3d_earth\scatter_sphere.py"/>
<OpenedFile File="D:\Working\MIScript\Jython\mis\common_math\integrate\odeint_1.py"/>
<OpenedFile File="D:\Working\MIScript\Jython\mis\common_math\integrate\odeint_lorenz.py"/>
<OpenedFile File="D:\Working\MIScript\Jython\mis\dataframe\dataframe_groupby_1.py"/>
<OpenedFile File="D:\Working\MIScript\Jython\mis\map\maskout\polygonindex_1.py"/>
</OpenedFiles>
<RecentFiles>
<RecentFile File="D:\Working\MIScript\Jython\mis\plot_types\3d\jogl\surf\surf_pumpkin_1.py"/>
<RecentFile File="D:\Working\MIScript\Jython\mis\plot_types\3d\3d_earth\scatter_sphere.py"/>
<RecentFile File="D:\Working\MIScript\Jython\mis\common_math\integrate\odeint_1.py"/>
<RecentFile File="D:\Working\MIScript\Jython\mis\common_math\integrate\odeint_lorenz.py"/>
<RecentFile File="D:\Working\MIScript\Jython\mis\dataframe\dataframe_groupby_1.py"/>
<RecentFile File="D:\Working\MIScript\Jython\mis\map\maskout\polygonindex_1.py"/>
</RecentFiles>
</File>
<Font>
@ -36,5 +34,5 @@
</Font>
<LookFeel DockWindowDecorated="true" LafDecorated="true" Name="FlatDarkLaf"/>
<Figure DoubleBuffering="true"/>
<Startup MainFormLocation="-7,0" MainFormSize="1367,792"/>
<Startup MainFormLocation="-7,0" MainFormSize="1381,848"/>
</MeteoInfo>

View File

@ -1,9 +1,9 @@
#-----------------------------------------------------
# -----------------------------------------------------
# Author: Yaqiang Wang
# Date: 2014-12-27
# Purpose: MeteoInfo geo module
# Note: Jython
#-----------------------------------------------------
# -----------------------------------------------------
import os
import numbers
@ -31,12 +31,13 @@ import mipylib.numeric as np
from java.util import ArrayList
__all__ = [
'arrayinpolygon','bilwrite','circle','convert_encoding_dbf','distance','georead','geotiffread','gridarea',
'maplayer','inpolygon','maskin','maskout','polyarea','polygon','rmaskin','rmaskout','shaperead',
'projinfo','project','projectxy','reproject','reproject_image'
]
'arrayinpolygon', 'bilwrite', 'circle', 'convert_encoding_dbf', 'distance', 'georead', 'geotiffread', 'gridarea',
'maplayer', 'inpolygon', 'maskin', 'maskout', 'polyarea', 'polygon', 'rmaskin', 'rmaskout', 'shaperead',
'polygonindex', 'projinfo', 'project', 'projectxy', 'reproject', 'reproject_image'
]
def shaperead(fn, encoding=None):
def shaperead(fn, encoding=None):
"""
Returns a layer readed from a shape file.
@ -49,8 +50,8 @@ def shaperead(fn, encoding=None):
fn = fn + '.shp'
if not os.path.exists(fn):
fn = os.path.join(migl.get_map_folder(), fn)
if os.path.exists(fn):
if os.path.exists(fn):
try:
if encoding is None:
encoding = IOUtil.encodingDetectShp(fn)
@ -65,9 +66,11 @@ def shaperead(fn, encoding=None):
except:
raise
else:
print 'File not exists: ' + fn
print
'File not exists: ' + fn
raise
def georead(fn, encoding=None):
"""
Returns a layer read from a supported geo-data file.
@ -82,7 +85,7 @@ def georead(fn, encoding=None):
if not os.path.exists(fn):
fn = fn + '.shp'
if os.path.exists(fn):
if fn.endswith('.shp'):
return shaperead(fn, encoding)
@ -99,7 +102,8 @@ def georead(fn, encoding=None):
else:
print('File not exists: ' + fn)
raise IOError
def geotiffread(filename):
"""
Return data array from a GeoTiff data file.
@ -112,7 +116,8 @@ def geotiffread(filename):
geotiff.read()
r = geotiff.readArray()
return NDArray(r)
def convert_encoding_dbf(filename, fromencoding, toencoding):
"""
Convert encoding of a dBase file (.dbf).
@ -121,16 +126,17 @@ def convert_encoding_dbf(filename, fromencoding, toencoding):
:param fromencoding: (*string*) From encoding.
:param toencoding: (*string*) To encoding.
"""
#Read dBase file
# Read dBase file
atable = AttributeTable()
atable.setEncoding(fromencoding)
atable.openDBF(filename)
atable.fill(atable.getNumRecords())
#Save dBase file
# Save dBase file
atable.setEncoding(toencoding)
atable.save()
def maplayer(shapetype='polygon'):
"""
Create a new map layer.
@ -141,7 +147,8 @@ def maplayer(shapetype='polygon'):
:returns: (*MILayer*) MILayer object.
"""
return MILayer(shapetype=shapetype)
def polygon(x, y=None):
"""
Create polygon from coordinate data.
@ -159,7 +166,8 @@ def polygon(x, y=None):
if isinstance(y, NDArray):
y = y.aslist()
polygon = ShapeUtil.createPolygonShape(x, y)
return polygon
return polygon
def circle(xy, radius=5):
"""
@ -171,8 +179,9 @@ def circle(xy, radius=5):
:returns: (*CircleShape*) Created circle.
"""
cc = ShapeUtil.createCircleShape(xy[0], xy[1], radius)
return cc
return cc
def inpolygon(x, y, polygon):
"""
Check if x/y points are inside a polygon or not.
@ -187,7 +196,7 @@ def inpolygon(x, y, polygon):
x = np.array([x])
if isinstance(y, numbers.Number):
y = np.array([y])
if isinstance(x, (list, tuple)):
x = np.array(x)
if isinstance(y, (list, tuple)):
@ -210,7 +219,8 @@ def inpolygon(x, y, polygon):
return r[0]
else:
return r
def arrayinpolygon(a, polygon, x=None, y=None):
"""
Set array element value as 1 if inside a polygon or set value as -1.
@ -226,6 +236,7 @@ def arrayinpolygon(a, polygon, x=None, y=None):
if x is None or y is None:
x = self.dimvalue(1)
y = self.dimvalue(0)
if not x is None and not y is None:
if isinstance(polygon, tuple):
x_p = polygon[0]
@ -241,7 +252,28 @@ def arrayinpolygon(a, polygon, x=None, y=None):
return NDArray(GeometryUtil.inPolygon(a.asarray(), x.aslist(), y.aslist(), polygon))
else:
return None
def polygonindex(x, y, polygons):
"""
Find polygon index by x, y coordinates.
:param x: (*float*) X coordinate of the point.
:param y: (*float*) Y coordinate of the point.
:param polygons: (*list of PolygonShape*) The polygons
:returns: (*array_like*) Result array.
"""
if isinstance(x, (tuple, list)):
x = np.array(x)
if isinstance(x, (tuple, list)):
y = np.array(y)
r = GeometryUtil.polygonIndex(x.jarray, y.jarray, polygons)
return NDArray(r)
def distance(*args, **kwargs):
"""
Get distance of a line.
@ -263,7 +295,8 @@ def distance(*args, **kwargs):
y = y.aslist()
r = GeoComputation.getDistance(x, y, islonlat)
return r
def polyarea(*args, **kwargs):
"""
Calculate area of polygon.
@ -288,6 +321,7 @@ def polyarea(*args, **kwargs):
r = GeoComputation.getArea(x, y, islonlat)
return r
def gridarea(x_orig, x_cell, x_num, y_orig, y_cell, y_num, islonlat=False,
allcell=True, earth_radius=None):
"""
@ -311,7 +345,8 @@ def gridarea(x_orig, x_cell, x_num, y_orig, y_cell, y_num, islonlat=False,
a = GeoComputation.getGridArea(x_orig, x_cell, x_num, y_orig, y_cell, y_num,
islonlat, allcell, earth_radius)
return NDArray(a)
def maskout(data, mask, x=None, y=None):
"""
Maskout data by polygons - NaN values of elements outside polygons.
@ -331,7 +366,7 @@ def maskout(data, mask, x=None, y=None):
return DimArray(r, data.dims, data.fill_value, data.proj)
else:
return NDArray(r)
if x is None or y is None:
if isinstance(data, DimArray):
x = data.dimvalue(data.ndim - 1)
@ -347,16 +382,17 @@ def maskout(data, mask, x=None, y=None):
for i in range(len(mask)):
if isinstance(mask[i], Graphic):
mask[i] = mask[i].getShape()
if data.ndim == 2 and x.ndim == 1 and y.ndim == 1:
x, y = np.meshgrid(x, y)
r = GeometryUtil.maskout(data._array, x._array, y._array, mask)
if isinstance(data, DimArray):
return DimArray(r, data.dims, data.fill_value, data.proj)
else:
return NDArray(r)
def rmaskout(data, x, y, mask):
"""
Maskout data by polygons - the elements outside polygons will be removed
@ -371,8 +407,9 @@ def rmaskout(data, x, y, mask):
if not isinstance(mask, (list, ArrayList)):
mask = [mask]
r = GeometryUtil.maskout_Remove(data.asarray(), x.asarray(), y.asarray(), mask)
return NDArray(r[0]), NDArray(r[1]), NDArray(r[2])
return NDArray(r[0]), NDArray(r[1]), NDArray(r[2])
def maskin(data, mask, x=None, y=None):
"""
Maskin data by polygons - NaN values of elements inside polygons.
@ -385,21 +422,21 @@ def maskin(data, mask, x=None, y=None):
:returns: (*array_like*) Maskined data array.
"""
if mask is None:
return data
return data
elif isinstance(mask, NDArray):
r = ArrayMath.maskin(data._array, mask._array)
if isinstance(data, DimArray):
return DimArray(r, data.dims, data.fill_value, data.proj)
else:
return NDArray(r)
if x is None or y is None:
if isinstance(data, DimArray):
x = data.dimvalue(data.ndim - 1)
y = data.dimvalue(data.ndim - 2)
else:
return None
if data.ndim == 2 and x.ndim == 1 and y.ndim == 1:
x, y = np.meshgrid(x, y)
@ -410,7 +447,8 @@ def maskin(data, mask, x=None, y=None):
return DimArray(r, data.dims, data.fill_value, data.proj)
else:
return NDArray(r)
def rmaskin(data, x, y, mask):
"""
Maskin data by polygons - the elements inside polygons will be removed
@ -425,8 +463,9 @@ def rmaskin(data, x, y, mask):
if not isinstance(mask, (list, ArrayList)):
mask = [mask]
r = GeometryUtil.maskin_Remove(data._array, x._array, y._array, mask)
return NDArray(r[0]), NDArray(r[1]), NDArray(r[2])
return NDArray(r[0]), NDArray(r[1]), NDArray(r[2])
def projinfo(proj4string=None, proj='longlat', **kwargs):
"""
Create a projection object with Proj.4 parameters (http://proj4.org/)
@ -450,7 +489,7 @@ def projinfo(proj4string=None, proj='longlat', **kwargs):
"""
if not proj4string is None:
return ProjectionInfo.factory(proj4string)
if proj == 'longlat' and len(kwargs) == 0:
return KnownCoordinateSystems.geographic.world.WGS1984
@ -522,10 +561,12 @@ def projinfo(proj4string=None, proj='longlat', **kwargs):
zone = kwargs.pop('zone', None)
if not zone is None:
projstr = projstr + ' +zone=' + str(zone)
return ProjectionInfo.factory(projstr)
def project(x, y, fromproj=KnownCoordinateSystems.geographic.world.WGS1984, toproj=KnownCoordinateSystems.geographic.world.WGS1984):
return ProjectionInfo.factory(projstr)
def project(x, y, fromproj=KnownCoordinateSystems.geographic.world.WGS1984,
toproj=KnownCoordinateSystems.geographic.world.WGS1984):
"""
Project geographic coordinates from one projection to another.
@ -551,7 +592,8 @@ def project(x, y, fromproj=KnownCoordinateSystems.geographic.world.WGS1984, topr
inpt = PointD(x, y)
outpt = Reproject.reprojectPoint(inpt, fromproj, toproj)
return outpt.X, outpt.Y
def projectxy(lon, lat, xnum, ynum, dx, dy, toproj, fromproj=None, pos='lowerleft'):
"""
Get projected x, y coordinates by projection and a given lon, lat coordinate.
@ -580,7 +622,8 @@ def projectxy(lon, lat, xnum, ynum, dx, dy, toproj, fromproj=None, pos='lowerlef
xx = np.arange1(llx, xnum, dx)
yy = np.arange1(lly, ynum, dy)
return xx, yy
def reproject(a, x=None, y=None, fromproj=None, xp=None, yp=None, toproj=None, method='bilinear'):
"""
Project array
@ -608,7 +651,7 @@ def reproject(a, x=None, y=None, fromproj=None, xp=None, yp=None, toproj=None, m
fromproj = a.proj
else:
fromproj = KnownCoordinateSystems.geographic.world.WGS1984
if toproj is None:
toproj = KnownCoordinateSystems.geographic.world.WGS1984
@ -629,6 +672,7 @@ def reproject(a, x=None, y=None, fromproj=None, xp=None, yp=None, toproj=None, m
r = Reproject.reproject(a.asarray(), x.aslist(), y.aslist(), xp, yp, fromproj, toproj, method)
return NDArray(r)
def reproject_image(a, x=None, y=None, fromproj=None, xp=None, yp=None, toproj=None):
"""
Project image data array
@ -668,6 +712,7 @@ def reproject_image(a, x=None, y=None, fromproj=None, xp=None, yp=None, toproj=N
r = Reproject.reprojectImage(a.asarray(), x.asarray(), y.asarray(), xp, yp, fromproj, toproj)
return NDArray(r)
def bilwrite(fn, data, x, y, proj=projinfo()):
"""
Write a bil file from a 2D array.
@ -678,4 +723,4 @@ def bilwrite(fn, data, x, y, proj=projinfo()):
:param y: (*array*) The y coordinate array - 1D.
:param proj: (*ProjectionInfo*) The projection. Default is long_lat projection.
"""
GeoIOUtil.saveAsBILFile(fn, data.asarray(), x.asarray(), y.asarray(), proj)
GeoIOUtil.saveAsBILFile(fn, data.asarray(), x.asarray(), y.asarray(), proj)

View File

@ -1,9 +1,9 @@
#-----------------------------------------------------
# -----------------------------------------------------
# Author: Yaqiang Wang
# Date: 2015-9-20
# Purpose: MeteoInfoLab layer module
# Note: Jython
#-----------------------------------------------------
# -----------------------------------------------------
import geoutil
import mipylib.miutil as miutil
import mipylib.numeric as np
@ -18,6 +18,7 @@ from org.meteoinfo.geometry.shape import PolygonShape, ShapeTypes
from org.meteoinfo.geo.analysis import GeometryUtil
from org.meteoinfo.geo.util import GeoProjectionUtil
class MILayer(object):
"""
Map layer
@ -26,6 +27,7 @@ class MILayer(object):
:param shapetype: (*ShapeTypes*) Shape type ['point' | 'point_z' | 'line' | 'line_z' | 'polygon'
| 'polygon_z']
"""
def __init__(self, layer=None, shapetype=None):
if layer is None:
if shapetype is None:
@ -49,7 +51,7 @@ class MILayer(object):
self.shapetype = layer.getShapeType()
self.proj = layer.getProjInfo()
self._coord_array = None
def __repr__(self):
return self._layer.getLayerInfo()
@ -104,7 +106,7 @@ class MILayer(object):
return np.array(self._coord_array[3])
else:
return None
def isvectorlayer(self):
"""
Check this layer is VectorLayer or not.
@ -112,7 +114,7 @@ class MILayer(object):
:returns: (*boolean*) Is VectorLayer or not.
"""
return self._layer.getLayerType() == LayerTypes.VECTOR_LAYER
def get_encoding(self):
"""
Get encoding.
@ -120,7 +122,17 @@ class MILayer(object):
:returns: (*string*) Encoding
"""
return self._layer.getAttributeTable().getEncoding()
@property
def datatable(self):
"""
Get attribute table.
:return: Attribute table.
"""
r = self._layer.getAttributeTable().getTable()
return np.datatable(r)
def gettable(self):
"""
Get attribute table.
@ -129,7 +141,7 @@ class MILayer(object):
"""
r = self._layer.getAttributeTable().getTable()
return np.datatable(r)
def cellvalue(self, fieldname, shapeindex):
"""
Get attribute table cell value.
@ -145,35 +157,50 @@ class MILayer(object):
return dt
else:
return v
def setcellvalue(self, fieldname, shapeindex, value):
"""
Set cell value in attribute table.
:param fieldname: (*string*) Field name.
:param shapeindex: (*int*) Shape index.
:param value: (*object*) Cell value to be asigned.
:param value: (*object*) Cell value to be assigned.
"""
self._layer.editCellValue(fieldname, shapeindex, value)
def setfieldvalue(self, fieldname, value, index=None):
"""
Set field value.
:param fieldname: (*str*) The field name.
:param value: (*array*) The field data array.
:param index: (*array*) Optional. Field data index. Default is `None`.
"""
value = np.asarray(value)
if index is None:
self._layer.getAttributeTable().getTable().setColumnData(fieldname, value.jarray)
else:
index = np.asarray(index)
self._layer.getAttributeTable().getTable().setColumnData(fieldname, value.jarray, index.jarray)
def shapes(self):
"""
Get shapes.
"""
return self._layer.getShapes()
def shapenum(self):
"""
Get shape number
"""
return self._layer.getShapeNum()
def legend(self):
"""
Get legend scheme.
"""
return self._layer.getLegendScheme()
def setlegend(self, legend):
"""
Set legend scheme.
@ -181,7 +208,7 @@ class MILayer(object):
:param legend: (*LegendScheme*) Legend scheme.
"""
self._layer.setLegendScheme(legend)
def update_legend(self, ltype, fieldname):
"""
Update legend scheme.
@ -199,7 +226,7 @@ class MILayer(object):
raise ValueError(ltype)
self._layer.updateLegendScheme(ltype, fieldname)
return self._layer.getLegendScheme()
def addfield(self, fieldname, dtype, values=None):
"""
Add a field into the attribute table.
@ -215,7 +242,7 @@ class MILayer(object):
for i in range(n):
if i < len(values):
self._layer.editCellValue(fieldname, i, values[i])
def delfield(self, fieldname):
"""
Delete a field from the attribute table.
@ -223,7 +250,7 @@ class MILayer(object):
:param fieldname: (*string*) Filed name.
"""
self._layer.editRemoveField(fieldname)
def renamefield(self, fieldname, newfieldname):
"""
Rename the field.
@ -232,7 +259,7 @@ class MILayer(object):
:param newfieldname: (*string*) The new field name.
"""
self._layer.editRenameField(fieldname, newfieldname)
def addshape(self, x, y, fields=None, z=None, m=None):
"""
Add a shape.
@ -266,7 +293,7 @@ class MILayer(object):
:param yshift: (*float*) Y shift.
"""
self._layer.move(xshift, yshift)
def addlabels(self, fieldname, **kwargs):
"""
Add labels
@ -306,7 +333,7 @@ class MILayer(object):
labelset.setAutoDecimal(False)
labelset.setDecimalDigits(decimals)
self._layer.addLabels()
def getlabel(self, text):
"""
Get a label.
@ -314,7 +341,7 @@ class MILayer(object):
:param text: (*string*) The label text.
"""
return self._layer.getLabel(text)
def movelabel(self, label, x=0, y=0):
"""
Move a label.
@ -324,7 +351,7 @@ class MILayer(object):
:param y: (*float*) Y shift for moving in pixel unit.
"""
self._layer.moveLabel(label, x, y)
def add_charts(self, fieldnames, legend=None, **kwargs):
"""
Add charts
@ -368,7 +395,7 @@ class MILayer(object):
font = Font(fontname, Font.PLAIN, fontsize)
labelcolor = kwargs.pop('labelcolor', None)
decimals = kwargs.pop('decimals', None)
chartset = self._layer.getChartSet()
chartset.setFieldNames(fieldnames)
chartset.setLegendScheme(legend)
@ -402,13 +429,13 @@ class MILayer(object):
self._layer.updateChartSet()
self._layer.addCharts()
return chartset
def get_chartlegend(self):
"""
Get legend of the chart graphics.
"""
return self._layer.getChartSet().getLegendScheme()
def get_chart(self, index):
"""
Get a chart graphic.
@ -418,7 +445,7 @@ class MILayer(object):
:returns: Chart graphic
"""
return self._layer.getChartPoints()[index]
def move_chart(self, index, x=0, y=0):
"""
Move a chart graphic.
@ -432,7 +459,7 @@ class MILayer(object):
p.X = p.X + x
p.Y = p.Y + y
s.setPoint(p)
def set_avoidcoll(self, avoidcoll):
"""
Set if avoid collision or not. Only valid for VectorLayer with Point shapes.
@ -440,7 +467,7 @@ class MILayer(object):
:param avoidcoll: (*boolean*) Avoid collision or not.
"""
self._layer.setAvoidCollision(avoidcoll)
def project(self, toproj):
"""
Project to another projection.
@ -448,7 +475,7 @@ class MILayer(object):
:param toproj: (*ProjectionInfo*) The projection to be projected.
"""
GeoProjectionUtil.projectLayer(self._layer, toproj)
def buffer(self, dist=0, merge=False):
"""
Get the buffer layer.
@ -460,7 +487,7 @@ class MILayer(object):
"""
r = self._layer.buffer(dist, False, merge)
return MILayer(r)
def clip(self, clipobj):
"""
Clip this layer by polygon or another polygon layer.
@ -475,7 +502,7 @@ class MILayer(object):
clipobj = clipobj._layer
r = self._layer.clip(clipobj)
return MILayer(r)
def select(self, expression, seltype='new'):
"""
Select shapes by SQL expression.
@ -488,19 +515,19 @@ class MILayer(object):
"""
self._layer.sqlSelect(expression, seltype)
return self._layer.getSelectedShapes()
def clear_selection(self):
"""
Clear shape selection.
"""
self._layer.clearSelectedShapes()
def clone(self):
"""
Clone self.
"""
return MILayer(self._layer.clone())
def save(self, fn=None, encoding=None):
"""
Save layer as shape file.
@ -510,7 +537,7 @@ class MILayer(object):
"""
if fn is None:
fn = self._layer.getFileName()
if fn.strip() == '':
print('File name is needed to save the layer!')
raise IOError
@ -519,7 +546,7 @@ class MILayer(object):
self._layer.saveFile(fn)
else:
self._layer.saveFile(fn, encoding)
def savekml(self, fn):
"""
Save layer as KML file.
@ -547,32 +574,31 @@ class MIXYListData():
self.data = XYListDataset()
else:
self.data = data
def __getitem__(self, indices):
if not isinstance(indices, tuple):
inds = []
inds.append(indices)
indices = inds
if isinstance(indices[0], int):
if isinstance(indices[1], int):
x = self.data.getX(indices[0], indices[1])
y = self.data.getY(indices[0], indices[1])
return x, y
else:
return self.data.getXValues(indices[0]), self.data.getXValues(indices[0])
return self.data.getXValues(indices[0]), self.data.getXValues(indices[0])
def size(self, series=None):
if series is None:
return self.data.getSeriesCount()
else:
return self.data.getItemCount(series)
def addseries(self, xdata, ydata, key=None):
if key is None:
key = 'Series_' + str(self.size())
if isinstance(xdata, list):
self.data.addSeries(key, xdata, ydata)
else:
self.data.addSeries(key, xdata.asarray(), ydata.asarray())
self.data.addSeries(key, xdata.asarray(), ydata.asarray())

View File

@ -37,6 +37,10 @@ class NDArray(object):
for i in range(1, self.ndim):
self.sizestr = self.sizestr + '*%s' % self.shape[i]
@property
def jarray(self):
return self._array
#---- shape property
def get_shape(self):
return self._shape
@ -1149,12 +1153,12 @@ class NDArray(object):
def ravel(self):
"""
Return a copy of the array collapsed into one dimension.
Return a contiguous flattened array.
:returns: (*NDArray*) A copy of the input array, flattened to one dimension.
:returns: (*NDArray*) A contiguous flattened array.
"""
shape = [self.size]
r = NDArray(self._array.reshape(shape))
r = NDArray(self._array.reshapeNoCopy(shape))
return r
def repeat(self, repeats, axis=None):

View File

@ -32,6 +32,8 @@
*/
package org.meteoinfo.ndarray;
import org.meteoinfo.common.util.JDateUtil;
import java.nio.ByteBuffer;
import java.nio.DoubleBuffer;
import java.time.LocalDateTime;
@ -181,11 +183,11 @@ public class ArrayDate extends Array {
}
public double getDouble(Index i) {
throw new ForbiddenConversionException();
return JDateUtil.toOADate(storage[i.currentElement()]);
}
public void setDouble(Index i, double value) {
throw new ForbiddenConversionException();
storage[i.currentElement()] = JDateUtil.fromOADate(value);
}
public float getFloat(Index i) {
@ -288,11 +290,11 @@ public class ArrayDate extends Array {
// trusted, assumes that individual dimension lengths have been checked
public double getDouble(int index) {
throw new ForbiddenConversionException();
return JDateUtil.toOADate(storage[index]);
}
public void setDouble(int index, double value) {
throw new ForbiddenConversionException();
storage[index] = JDateUtil.fromOADate(value);
}
public float getFloat(int index) {

View File

@ -121,7 +121,7 @@ public class DataRow {
}
/**
* Set a vlaue
* Set a value
*
* @param column The data column
* @param value The value

View File

@ -14,6 +14,7 @@
package org.meteoinfo.table;
import org.meteoinfo.common.MIMath;
import org.meteoinfo.ndarray.Array;
import org.meteoinfo.ndarray.DataType;
import org.meteoinfo.ndarray.Range;
import org.meteoinfo.table.util.TableUtil;
@ -608,6 +609,86 @@ public class DataTable {
setColumnData(col, colData);
}
/**
* Add column data
*
* @param col The column
* @param colData The column data
* @throws Exception
*/
public void setColumnData(DataColumn col, Array colData) throws Exception {
colData = colData.copyIfView();
if (this.getRowCount() == 0) {
for (int i = 0; i < colData.getSize(); i++){
DataRow row = this.addRow();
row.setValue(col, colData.getObject(i));
}
} else {
int i = 0;
for (DataRow row : this.rows) {
if (i < colData.getSize()) {
row.setValue(col, colData.getObject(i));
}
i++;
}
}
}
/**
* Add column data
*
* @param colName Column name
* @param colData The column data
* @throws Exception
*/
public void setColumnData(String colName, Array colData) throws Exception {
DataColumn col = this.findColumn(colName);
if (col == null){
System.out.println("The column not exists: " + colName + "!");
return;
}
setColumnData(col, colData);
}
/**
* Add column data
*
* @param col The column
* @param colData The column data
* @param index Data index array
* @throws Exception
*/
public void setColumnData(DataColumn col, Array colData, Array index) throws Exception {
colData = colData.copyIfView();
index = index.copyIfView();
int idx;
for (int i = 0; i < index.getSize(); i++) {
idx = index.getInt(i);
if (idx >=0 && idx < this.getRowCount())
this.rows.get(idx).setValue(col, colData.getObject(i));
}
}
/**
* Add column data
*
* @param colName Column name
* @param colData The column data
* @param index Data index array
* @throws Exception
*/
public void setColumnData(String colName, Array colData, Array index) throws Exception {
DataColumn col = this.findColumn(colName);
if (col == null){
System.out.println("The column not exists: " + colName + "!");
return;
}
setColumnData(col, colData, index);
}
/**
* Add column data
*