Exemple #1
0
class MultiLineString(_MultiLineString):
    """
  A MultiLineString geometry.

  *linestrings* is a variable number of lists of ``list``/``tuple`` arugments.

  >>> MultiLineString([[1,2],[3,4]], [[5,6],[7,8]])
  MULTILINESTRING ((1 2, 3 4), (5 6, 7 8))

  *linestrings* may also be specified as multiple :class:`LineString` arguments.

  >>> MultiLineString(LineString([1,2],[3,4]), LineString([5,6],[7,8]))
  MULTILINESTRING ((1 2, 3 4), (5 6, 7 8))

  """
    def __init__(self, *linestrings):

        if isinstance(linestrings[0], _MultiLineString):
            mls = linestrings[0]
            linestrings = [
                mls.getGeometryN(i) for i in range(mls.numGeometries)
            ]
        elif isinstance(linestrings[0], (list, tuple)):
            linestrings = [LineString(*l) for l in linestrings]

        _MultiLineString.__init__(self, linestrings, geom._factory)


geom._enhance(MultiLineString)
core.registerTypeMapping(_MultiLineString, MultiLineString)
Exemple #2
0
    features = self._source.features
    fc = WfsFactory.eINSTANCE.createFeatureCollectionType()
    fc.feature.add(features)

    e = Encoder(WFSConfiguration())        
    uri = self._source.name.namespaceURI
    prefix = 'gt'
    e.namespaces.declarePrefix(prefix,uri)
    e.indenting = True
    e.encode(fc, WFS.FeatureCollection, out)

  def toJSON(self,out=sys.stdout):
    try:
      from org.geotools.geojson import GeoJSONWriter
    except ImportError:
      raise Exception('toJSON() not available, GeoJSON libraries not on classpath.')
    else:
      features = self._source.features
      w = GeoJSONWriter() 
      w.write(features,out)

  @staticmethod
  def _newname():
    Layer._id  += 1
    return 'layer_%d' % Layer._id

core.registerTypeMapping(FeatureSource, Layer, lambda x: Layer(source=x))
core.registerTypeMapping(FeatureCollection, Layer, lambda x: Layer(source=x))
core.registerTypeUnmapping(Layer, FeatureSource, lambda x: x._source)
core.registerTypeUnmapping(Layer, FeatureCollection, lambda x: x._source.getFeatures())
Exemple #3
0
   The ``res`` argument is the resolution to tile at and should be in the range
   (0,1].
   """
   dx = self.width * res
   dy = self.height * res

   y = self.south
   while y < self.north:
     x = self.west
     while x < self.east:
       yield Bounds(x,y,min(x+dx,self.east),min(y+dy,self.north),self.proj)
       x += dx
     y += dy

  def __add__(self, other):
    b = Bounds(env=self)
    if self.proj and other.proj and other.proj != self.proj:
      other = other.reproject(self.proj)
    b.expandToInclude(other)
    return b
    
  def __repr__(self):
    s = '(%s, %s, %s, %s' % (self.west, self.south, self.east, self.north)
    if self.proj:
      s = '%s, %s' % (s, self.proj.id)

    return '%s)' % s

core.registerTypeMapping(ReferencedEnvelope, Bounds, lambda x: Bounds(env=x))

Exemple #4
0
from geoscript import core
import geom


class LineString(_LineString):
    """
  A LineString geometry.

  *coords* is a variable list of ``list``/``tuple`` arguments.

  >>> LineString([1,2], [3,4])
  LINESTRING (1 2, 3 4)
  """
    def __init__(self, *coords):

        if len(coords) == 1 and isinstance(coords[0], _LineString):
            ls = coords[0]
        else:
            l = []
            for c in coords:
                l.append(Coordinate(c[0], c[1]))
                if len(c) > 2:
                    l[-1].z = c[2]
            ls = geom._factory.createLineString(l)

        _LineString.__init__(self, ls.coordinateSequence, geom._factory)


geom._enhance(LineString)
core.registerTypeMapping(_LineString, LineString)
Exemple #5
0
        return self.schema.__iter__()

    def iterkeys(self):
        return self.__iter__()

    def iteritems(self):
        return self.attributes.iteritems()

    def keys(self):
        return [f.name for f in self.schema.fields]

    def values(self):
        return [core.map(val) for val in self._feature.getAttributes()]

    def __repr__(self):
        atts = [
            '%s: %s' % (fld.name, self.get(fld.name))
            for fld in self.schema.fields
        ]

        id = self.id if self.id.startswith(
            self.schema.name) else '%s.%s' % (self.schema.name, self.id)
        return '%s {%s}' % (id, string.join(atts, ', '))

    def __eq__(self, other):
        return other and self._feature == other._feature


core.registerTypeMapping(_Feature, Feature, lambda x: Feature(f=x))
core.registerTypeUnmapping(Feature, _Feature, lambda x: x._feature)
Exemple #6
0
      return percentAlong
  
  def placePoint(self, *coord):
      """
      Place or snap the :class:`point <geoscript.geom.Point>` to the `LineString <geoscript.geom.LineString>`. This method returns a new placed `Point <geoscript.geom.Point>`.

      *coord* A :class:`Point <geoscript.geom.Point>` or a variable list of x,y,z arguments.

      """
      point = coord[0] if isinstance(coord[0], Point) else Point(*coord)
      indexedLine = LengthIndexedLine(self)
      position = indexedLine.indexOf(point.coordinate)
      coord = indexedLine.extractPoint(position)
      return Point(coord.x, coord.y)
  
  def subLine(self, start, end):
      """
      Extract a sub :class:`LineString <geoscript.geom.LineString>` using a start and end position.  Both positions are numbers between 0 and 1.  A new :class:`LineString <geoscript.geom.LineString>` is returned.

      *start* The start position between 0 and 1
      
      *end* The end position between 0 and 1

      """
      indexedLine = LengthIndexedLine(self)
      length = self.getLength()
      return LineString(indexedLine.extractLine(start * length, end * length))

geom._enhance(LineString)
core.registerTypeMapping(_LineString, LineString)
Exemple #7
0
        result = self._op('Invert', Source=self._coverage)
        return Raster(self._format, coverage=result, reader=self._reader)

    def __invert__(self):
        pass

    def _op(self, name, **params):
        op = CoverageProcessor.getInstance().getOperation(name)
        p = op.getParameters()
        for k, v in params.iteritems():
            p.parameter(k).setValue(v)

        return op.doOperation(p, None)


core.registerTypeMapping(GridCoverage2D, Raster,
                         lambda x: Raster(None, coverage=x))
core.registerTypeUnmapping(Raster, GridCoverage2D, lambda x: x._coverage)


class Histogram(object):
    def __init__(self, histo):
        self._histo = histo

    def bin(self, i, band=0):
        h = self._histo
        if i < h.getNumBins(band):
            return (h.getBinLowValue(band, i), h.getBinLowValue(band, i + 1))

    def bins(self, band=0):
        return [self.bin(i, band) for i in range(len(self))]
Exemple #8
0
    def __getitem__(self, key):
        return self.get(key)

    def __iter__(self):
        for f in self.fields:
            yield f.name

    def iterkeys(self):
        return self.__iter__()

    def iteritems(self):
        for f in self.fields:
            yield f.name, f

    def keys(self):
        return [f.name for f in self.fields]

    def values(self):
        return self.fields

    def __repr__(self):
        flds = ['%s' % str(fld) for fld in self.fields]
        return '%s [%s]' % (self.name, string.join(flds, ', '))

    def __eq__(self, other):
        return other and self._type == other._type


core.registerTypeMapping(FeatureType, Schema, lambda x: Schema(ft=x))
core.registerTypeUnmapping(Schema, FeatureType, lambda x: x._type)
Exemple #9
0
from com.vividsolutions.jts.geom import Coordinate
from com.vividsolutions.jts.geom import Point as _Point
from geoscript import core
import geom

class Point(_Point):
  """
  A Point geometry.

  *coord* is a variable list of x, y, z arguments.

  >>> Point(1,2)
  POINT (1 2)
  """

  def __init__(self, *coord):

    if len(coord) == 1 and isinstance(coord[0], _Point):
      p = coord[0]
    else:
      c = Coordinate(coord[0], coord[1])
      if len(coord) > 2:
        c.z = coord[2]
      p = geom._factory.createPoint(c)

    _Point.__init__(self, p.coordinateSequence, geom._factory)

geom._enhance(Point)
core.registerTypeMapping(_Point, Point)
Exemple #10
0
from com.vividsolutions.jts.geom import Coordinate
from com.vividsolutions.jts.geom import LinearRing as _LinearRing
from linestring import LineString
from geoscript import core
import geom


class LinearRing(_LinearRing):
    """
  A LineString geometry in which the first and last coordinates are identical forming a closed ring. The arguments for contstructing a ``LinearRing`` are identical to those for constructing a :class:`LineString`. 

  >>> LinearRing([1,2], [3,4], [4,5], [1,2])
  LINEARRING (1 2, 3 4, 4 5, 1 2)
  """
    def __init__(self, *coords):
        if len(coords) == 1 and isinstance(coords[0], _LinearRing):
            _LinearRing.__init__(self, coords[0].coordinateSequence)
        else:
            l = LineString(*coords)
            _LinearRing.__init__(self, l.coordinateSequence, geom._factory)


geom._enhance(LinearRing)
core.registerTypeMapping(_LinearRing, LinearRing)
Exemple #11
0
  def __neg__(self): 
    result = self._op('Invert', Source=self._coverage)
    return Raster(self._format, coverage=result, reader=self._reader)
    
  def __invert__(self):
    pass

  def _op(self, name, **params):
    op = CoverageProcessor.getInstance().getOperation(name)
    p = op.getParameters()
    for k,v in params.iteritems():
      p.parameter(k).setValue(v)

    return op.doOperation(p, None)

core.registerTypeMapping(GridCoverage2D, Raster, lambda x: Raster(None, coverage=x))
core.registerTypeUnmapping(Raster, GridCoverage2D, lambda x: x._coverage)

class Histogram(object):

  def __init__(self, histo):
    self._histo = histo

  def bin(self, i, band=0):
    h = self._histo
    if i < h.getNumBins(band):
      return (h.getBinLowValue(band, i), h.getBinLowValue(band, i+1))

  def bins(self, band=0):
    return [self.bin(i, band) for i in range(len(self))]
Exemple #12
0
  POINT (1071693 554290)

  .. seealso:: 

     :func:`Projection.transform`
  """

    return Projection(src).transform(obj, dst)


def projections():
    """
  Iterator over all defined projections::

    for p in proj.projections():
       ..

  This function returns :class:`Projection` objects.

  """
    for code in crs.getSupportedCodes('epsg'):
        try:
            yield Projection('epsg:%s' % code)
        except:
            # todo: log this
            pass


core.registerTypeMapping(CRS, Projection)
core.registerTypeUnmapping(Projection, CRS, lambda x: x._crs)
Exemple #13
0
      raise Exception('toGML() not available, GML libraries not on classpath.') 

    features = self._source.features
    fc = WfsFactory.eINSTANCE.createFeatureCollectionType()
    fc.feature.add(features)

    e = Encoder(WFSConfiguration())        
    uri = self._source.name.namespaceURI
    prefix = 'gt'
    e.namespaces.declarePrefix(prefix,uri)
    e.indenting = True
    e.encode(fc, WFS.FeatureCollection, out)

  def toJSON(self,out=sys.stdout):
    try:
      from org.geotools.geojson import GeoJSONWriter
    except ImportError:
      raise Exception('toJSON() not available, GeoJSON libraries not on classpath.')
    else:
      features = self._source.features
      w = GeoJSONWriter() 
      w.write(features,out)

  @staticmethod
  def _newname():
    Layer._id  += 1
    return 'layer_%d' % Layer._id

core.registerTypeMapping(FeatureSource, Layer, lambda x: Layer(fs=x))
core.registerTypeUnmapping(Layer, FeatureSource, lambda x: x._source)
Exemple #14
0
import geom

class Polygon(_Polygon):
  """
  A Polygon geometry.

  *rings* is a variable number of lists of ``list``/``tuple`` arguments defining the rings of the polygon. The first argument is the outer ring and remaining arguments are holes. 

  >>> Polygon( [[1,2], [3,4], [5,6], [1,2]])
  POLYGON ((1 2, 3 4, 5 6, 1 2))
 
  >>> Polygon( [[-10,-10],[10,-10],[10,10],[-10,10],[-10,-10]], [[-5,-5],[-1,-5],[-3,-2],[-5,-5]], [[5,5],[9,5],[7,7],[5,5]] )
  POLYGON ((-10 -10, 10 -10, 10 10, -10 10, -10 -10), (-5 -5, -1 -5, -3 -2, -5 -5), (5 5, 9 5, 7 7, 5 5))

  *rings* may also be specified as a variable number of :class:`LinearRing` objects.

  >>> Polygon( LinearRing([-10,-10],[10,-10],[10,10],[-10,10],[-10,-10]), LinearRing([-5,-5],[-1,-5],[-3,-2],[-5,-5]), LinearRing([5,5],[9,5],[7,7],[5,5]) )
  POLYGON ((-10 -10, 10 -10, 10 10, -10 10, -10 -10), (-5 -5, -1 -5, -3 -2, -5 -5), (5 5, 9 5, 7 7, 5 5))
  """

  def __init__(self, *rings):
    if isinstance(rings[0], _Polygon):
      p = rings[0]
      _Polygon.__init__(self, p.exteriorRing, [p.getInteriorRingN(i) for i in range(p.numInteriorRing)], geom._factory)
    else:
      lr = [r if isinstance(r,LinearRing) else LinearRing(*r) for r in rings ]
      _Polygon.__init__(self, lr[0], lr[1:], geom._factory)

geom._enhance(Polygon)
core.registerTypeMapping(_Polygon, Polygon)

class MultiPoint(_MultiPoint):
    """
  A MultiPoint goemetry.

  *points* is a variable number of ``list``/``tuple`` arguments. 

  >>> MultiPoint([1,2], [3,4])
  MULTIPOINT ((1 2), (3 4))

  *points* may also be specified as a variable number of :class:`Point` arguments. 

  >>> MultiPoint(Point(1,2), Point(3,4))
  MULTIPOINT ((1 2), (3 4))
   
  """
    def __init__(self, *points):

        if isinstance(points[0], _MultiPoint):
            mp = points[0]
            points = [mp.getGeometryN(i) for i in range(mp.numGeometries)]
        elif isinstance(points[0], (list, tuple)):
            points = [Point(*p) for p in points]

        _MultiPoint.__init__(self, points, geom._factory)


geom._enhance(MultiPoint)
core.registerTypeMapping(_MultiPoint, MultiPoint)
Exemple #16
0
  def __getitem__(self, key):
    return self.get(key)

  def __iter__(self):
    for f in self.fields:
      yield f.name

  def iterkeys(self):
    return self.__iter__()

  def iteritems(self):
    for f in self.fields:
      yield f.name, f

  def keys(self):
    return [f.name for f in self.fields] 

  def values(self):
    return self.fields

  def __repr__(self):
    flds = ['%s' % str(fld) for fld in self.fields]
    return '%s [%s]' % (self.name, string.join(flds,', '))

  def __eq__(self, other):
    return other and self._type == other._type

core.registerTypeMapping(FeatureType, Schema, lambda x: Schema(ft=x))
core.registerTypeUnmapping(Schema, FeatureType, lambda x: x._type)
Exemple #17
0
  ogc, ogcconfig  = _ogc(version)
  parser = Parser(ogcconfig)
  return parser.parse(io.StringReader(xml))

def _toXML(filter, pretty=True, version=1.0):
  """
  Encodes a filter object as XML.

  """

  ogc, ogcconfig = _ogc(version)
  e = Encoder(ogcconfig)
  e.indenting = pretty
  e.omitXMLDeclaration = True
  out = io.ByteArrayOutputStream()
  e.encode(filter, ogc.Filter, out)
  return str(lang.String(out.toByteArray()))
 
def _ogc(version):
  try: 
    from org.geotools.filter.v1_0 import OGCConfiguration as OGCConfiguration10, OGC as OGC10
    from org.geotools.filter.v1_1 import OGCConfiguration as OGCConfiguration11, OGC as OGC11

  except ImportError:
    raise Exception('fromXML() not available, filter libs not on classpath')

  return (OGC11.getInstance(),OGCConfiguration11()) if version == 1.1 else (OGC10.getInstance(), OGCConfiguration10())

core.registerTypeMapping(_Filter, Filter)
core.registerTypeMapping(Filter, _Filter, lambda x: x._filter)
Exemple #18
0
       self.get(key) 

       #todo: drop the existing schema and create a new one
       raise Exception('%s already exists' % key) 
     except KeyError:
       if isinstance(val, list):
         self.create(key, fields=val)
       elif isinstance(val, feature.Schema):
         self.create(key, schema=val)
       else: 
         self.add(val)

  def __iter__(self):
    return self.layers().__iter__()

  def iterkeys(self):
    return self.__iter__()

  def iteritems(self):
    for l in self.layers():
       yield (l, self.get(l)) 

  def keys(self):
    return self.layers()

  def values(self):
    return [v for k,v in self.iteritems()]

core.registerTypeMapping(DataStore, Workspace, lambda x: Workspace(ds=x))
core.registerTypeUnmapping(Workspace, DataStore, lambda x: x._store)
Exemple #19
0
from org.geotools.geometry.jts import CurvedGeometryFactory
from linestring import LineString
from circularstring import CircularString
from java.lang import Double
from geoscript import core
import geom

class CompoundRing(_CompoundRing):
    """
    A CompoundRing geometry.

    *linestrings* is a variable list of ``LineStrings`` or ``CircularStrings`` arguments.

    >>> CompoundRing(CircularString([10.0, 10.0], [0.0, 20.0], [-10.0, 10.0]),LineString([-10.0, 10.0], [-10.0, 0.0], [10.0, 0.0], [10.0, 10.0]))
    COMPOUNDCURVE(CIRCULARSTRING(10.0 10.0, 0.0 20.0, -10.0 10.0), (-10.0 10.0, -10.0 0.0, 10.0 0.0, 10.0 10.0))
    """

    def __init__(self, *linestrings):
        tolerance = Double.MAX_VALUE    
        if len(linestrings) == 1 and isinstance(linestrings[0], _CompoundRing):
            cc = linestrings[0]
            linestrings = cc.components

        cgf = CurvedGeometryFactory(tolerance)
        _CompoundRing.__init__(self, linestrings, cgf, tolerance)

geom._enhance(CompoundRing)
core.registerTypeMapping(_CompoundRing, CompoundRing)


Exemple #20
0
from org.geotools.geometry.jts import CompoundRing as _CompoundRing
from org.geotools.geometry.jts import CurvedGeometryFactory
from linestring import LineString
from circularstring import CircularString
from java.lang import Double
from geoscript import core
import geom


class CompoundRing(_CompoundRing):
    """
    A CompoundRing geometry.

    *linestrings* is a variable list of ``LineStrings`` or ``CircularStrings`` arguments.

    >>> CompoundRing(CircularString([10.0, 10.0], [0.0, 20.0], [-10.0, 10.0]),LineString([-10.0, 10.0], [-10.0, 0.0], [10.0, 0.0], [10.0, 10.0]))
    COMPOUNDCURVE(CIRCULARSTRING(10.0 10.0, 0.0 20.0, -10.0 10.0), (-10.0 10.0, -10.0 0.0, 10.0 0.0, 10.0 10.0))
    """
    def __init__(self, *linestrings):
        tolerance = Double.MAX_VALUE
        if len(linestrings) == 1 and isinstance(linestrings[0], _CompoundRing):
            cc = linestrings[0]
            linestrings = cc.components

        cgf = CurvedGeometryFactory(tolerance)
        _CompoundRing.__init__(self, linestrings, cgf, tolerance)


geom._enhance(CompoundRing)
core.registerTypeMapping(_CompoundRing, CompoundRing)
Exemple #21
0
from org.geotools.geometry.jts import CompoundCurve as _CompoundCurve
from org.geotools.geometry.jts import CurvedGeometryFactory
from linestring import LineString
from circularstring import CircularString
from java.lang import Double
from geoscript import core
import geom

class CompoundCurve(_CompoundCurve):
    """
    A CompoundCurve geometry.

    *linestrings* is a variable list of ``LineStrings`` or ``CircularStrings`` arguments.

    >>> CompoundCurve(CircularString([10.0, 10.0], [0.0, 20.0], [-10.0, 10.0]), LineString([-10.0, 10.0], [-10.0, 0.0], [10.0, 0.0], [5.0, 5.0]))
    COMPOUNDCURVE(CIRCULARSTRING(10.0 10.0, 0.0 20.0, -10.0 10.0), (-10.0 10.0, -10.0 0.0, 10.0 0.0, 5.0 5.0))
    """

    def __init__(self, *linestrings):
        tolerance = Double.MAX_VALUE    
        if len(linestrings) == 1 and isinstance(linestrings[0], _CompoundCurve):
            cc = linestrings[0]
            linestrings = cc.components

        cgf = CurvedGeometryFactory(tolerance)
        _CompoundCurve.__init__(self, linestrings, cgf, tolerance)

geom._enhance(CompoundCurve)
core.registerTypeMapping(_CompoundCurve, CompoundCurve)

Exemple #22
0
  >>> p2.round()
  POINT (1071693 554290)

  .. seealso:: 

     :func:`Projection.transform`
  """
  
  return Projection(src).transform(obj, dst)

def projections():
  """
  Iterator over all defined projections::

    for p in proj.projections():
       ..

  This function returns :class:`Projection` objects.

  """
  for code in crs.getSupportedCodes('epsg'):
     try:
       yield Projection('epsg:%s' % code)
     except:
       # todo: log this
       pass

core.registerTypeMapping(CRS, Projection)
core.registerTypeUnmapping(Projection, CRS, lambda x: x._crs)

Exemple #23
0
from com.vividsolutions.jts.geom import Coordinate
from com.vividsolutions.jts.geom import LinearRing as _LinearRing
from linestring import LineString
from geoscript import core
import geom

class LinearRing(_LinearRing):
  """
  A LineString geometry in which the first and last coordinates are identical forming a closed ring. The arguments for contstructing a ``LinearRing`` are identical to those for constructing a :class:`LineString`. 

  >>> LinearRing([1,2], [3,4], [4,5], [1,2])
  LINEARRING (1 2, 3 4, 4 5, 1 2)
  """

  def __init__(self, *coords):
    if len(coords) == 1 and isinstance(coords[0], _LinearRing):
      _LinearRing.__init__(self, coords[0].coordinateSequence) 
    else:
      l = LineString(*coords)
      _LinearRing.__init__(self, l.coordinateSequence, geom._factory)

geom._enhance(LinearRing)
core.registerTypeMapping(_LinearRing, LinearRing)
import geom

class MultiPolygon(_MultiPolygon):
  """
  A MultiPolygon geometry.

  *polygons* is a variable number of multidimensional lists of ``list``/``tuple``.

  >>> MultiPolygon( [ [[1,2],[3,4],[5,6],[1,2]] ],  [ [[7,8], [9,10], [11,12], [7,8]] ] )
  MULTIPOLYGON (((1 2, 3 4, 5 6, 1 2)), ((7 8, 9 10, 11 12, 7 8)))

  *polygons* may also be specified as a variable number of :class:`Polygon` arguments.

  >>> MultiPolygon(Polygon([[1,2], [3,4], [5,6], [1,2]]), Polygon([[7,8], [9,10], [11,12], [7,8]]))
  MULTIPOLYGON (((1 2, 3 4, 5 6, 1 2)), ((7 8, 9 10, 11 12, 7 8)))
  
  """

  def __init__(self, *polygons):
  
    if isinstance(polygons[0], _MultiPolygon):
       mp = polygons[0]
       polygons = [mp.getGeometryN(i) for i in range(mp.numGeometries)]
    elif isinstance(polygons[0], (list,tuple)):
       polygons = [Polygon(*p) for p in polygons]

    _MultiPolygon.__init__(self, polygons, geom._factory)

geom._enhance(MultiPolygon)
core.registerTypeMapping(_MultiPolygon, MultiPolygon)
Exemple #25
0
        e = Encoder(WFSConfiguration())
        uri = self._source.name.namespaceURI
        prefix = 'gt'
        e.namespaces.declarePrefix(prefix, uri)
        e.indenting = True
        e.encode(fc, WFS.FeatureCollection, out)

    def toJSON(self, out=sys.stdout):
        try:
            from org.geotools.geojson import GeoJSONWriter
        except ImportError:
            raise Exception(
                'toJSON() not available, GeoJSON libraries not on classpath.')
        else:
            features = self._source.features
            w = GeoJSONWriter()
            w.write(features, out)

    @staticmethod
    def _newname():
        Layer._id += 1
        return 'layer_%d' % Layer._id


core.registerTypeMapping(FeatureSource, Layer, lambda x: Layer(source=x))
core.registerTypeMapping(FeatureCollection, Layer, lambda x: Layer(source=x))
core.registerTypeUnmapping(Layer, FeatureSource, lambda x: x._source)
core.registerTypeUnmapping(Layer, FeatureCollection,
                           lambda x: x._source.getFeatures())
Exemple #26
0
  def __setitem__(self, key, value):
    self.set(key, value)

  def __iter__(self):
    return self.schema.__iter__()

  def iterkeys(self):
    return self.__iter__()

  def iteritems(self):
    return self.attributes.iteritems()

  def keys(self):
    return [f.name for f in self.schema.fields]

  def values(self):
    return [core.map(val) for val in self._feature.getAttributes()]

  def __repr__(self):
    atts = ['%s: %s' % (fld.name, self.get(fld.name)) for fld in self.schema.fields]

    id = self.id if self.id.startswith(self.schema.name) else '%s.%s' % (self.schema.name, self.id)
    return '%s {%s}' % (id, string.join(atts,', '))

  def __eq__(self, other):
    return other and self._feature == other._feature

core.registerTypeMapping(_Feature, Feature, lambda x: Feature(f=x))
core.registerTypeUnmapping(Feature, _Feature, lambda x: x._feature)
Exemple #27
0
import geom

class Polygon(_Polygon):
  """
  A Polygon geometry.

  *rings* is a variable number of lists of ``list``/``tuple`` arguments defining the rings of the polygon. The first argument is the outer ring and remaining arguments are holes. 

  >>> Polygon( [[1,2], [3,4], [5,6], [1,2]])
  POLYGON ((1 2, 3 4, 5 6, 1 2))
 
  >>> Polygon( [[-10,-10],[10,-10],[10,10],[-10,10],[-10,-10]], [[-5,-5],[-1,-5],[-3,-2],[-5,-5]], [[5,5],[9,5],[7,7],[5,5]] )
  POLYGON ((-10 -10, 10 -10, 10 10, -10 10, -10 -10), (-5 -5, -1 -5, -3 -2, -5 -5), (5 5, 9 5, 7 7, 5 5))

  *rings* may also be specified as a variable number of :class:`LinearRing` objects.

  >>> Polygon( LinearRing([-10,-10],[10,-10],[10,10],[-10,10],[-10,-10]), LinearRing([-5,-5],[-1,-5],[-3,-2],[-5,-5]), LinearRing([5,5],[9,5],[7,7],[5,5]) )
  POLYGON ((-10 -10, 10 -10, 10 10, -10 10, -10 -10), (-5 -5, -1 -5, -3 -2, -5 -5), (5 5, 9 5, 7 7, 5 5))
  """

  def __init__(self, *rings):
    if isinstance(rings[0], _Polygon):
      p = rings[0]
      _Polygon.__init__(self, p.exteriorRing, [p.getInteriorRingN(i) for i in range(p.numInteriorRing)], geom._factory)
    else:
      lr = [r if isinstance(r,LinearRing) else LinearRing(*r) for r in rings ]
      _Polygon.__init__(self, lr[0], lr[1:], geom._factory)

geom._enhance(Polygon)
core.registerTypeMapping(_Polygon, Polygon)
    A CircularRing geometry.

    *coords* is a variable list of ``list``/``tuple`` arguments.

    >>> CircularRing([1,1], [5,5], [2,2], [4,5], [1,1])
    CIRCULARSTRING (1.0 1.0, 5.0 5.0, 2.0 2.0, 4.0 5.0, 1.0 1.0)
    """

    def __init__(self, *coords):
        tolerance = Double.MAX_VALUE    
        if len(coords) == 1 and isinstance(coords[0], _CircularRing):
          cs = coords[0].coordinateSequence
        else:
          l = []
          for c in coords:
            l.append( Coordinate(c[0],c[1]) )
            if len(c) > 2:
              l[-1].z = c[2]
          cs = geom._factory.coordinateSequenceFactory.create(l)
        
        doubles = []
        for c in cs.toCoordinateArray():
            doubles.append(c.x)
            doubles.append(c.y)

        cgf = CurvedGeometryFactory(tolerance)
        _CircularRing.__init__(self, doubles, cgf, tolerance)

geom._enhance(CircularRing)
core.registerTypeMapping(_CircularRing, CircularRing)
Exemple #29
0

class MultiPolygon(_MultiPolygon):
    """
  A MultiPolygon geometry.

  *polygons* is a variable number of multidimensional lists of ``list``/``tuple``.

  >>> MultiPolygon( [ [[1,2],[3,4],[5,6],[1,2]] ],  [ [[7,8], [9,10], [11,12], [7,8]] ] )
  MULTIPOLYGON (((1 2, 3 4, 5 6, 1 2)), ((7 8, 9 10, 11 12, 7 8)))

  *polygons* may also be specified as a variable number of :class:`Polygon` arguments.

  >>> MultiPolygon(Polygon([[1,2], [3,4], [5,6], [1,2]]), Polygon([[7,8], [9,10], [11,12], [7,8]]))
  MULTIPOLYGON (((1 2, 3 4, 5 6, 1 2)), ((7 8, 9 10, 11 12, 7 8)))
  
  """
    def __init__(self, *polygons):

        if isinstance(polygons[0], _MultiPolygon):
            mp = polygons[0]
            polygons = [mp.getGeometryN(i) for i in range(mp.numGeometries)]
        elif isinstance(polygons[0], (list, tuple)):
            polygons = [Polygon(*p) for p in polygons]

        _MultiPolygon.__init__(self, polygons, geom._factory)


geom._enhance(MultiPolygon)
core.registerTypeMapping(_MultiPolygon, MultiPolygon)
Exemple #30
0
    A CircularRing geometry.

    *coords* is a variable list of ``list``/``tuple`` arguments.

    >>> CircularRing([1,1], [5,5], [2,2], [4,5], [1,1])
    CIRCULARSTRING(1.0 1.0, 5.0 5.0, 2.0 2.0, 4.0 5.0, 1.0 1.0)
    """
    def __init__(self, *coords):
        tolerance = Double.MAX_VALUE
        if len(coords) == 1 and isinstance(coords[0], _CircularRing):
            cs = coords[0].coordinateSequence
        else:
            l = []
            for c in coords:
                l.append(Coordinate(c[0], c[1]))
                if len(c) > 2:
                    l[-1].z = c[2]
            cs = geom._factory.coordinateSequenceFactory.create(l)

        doubles = []
        for c in cs.toCoordinateArray():
            doubles.append(c.x)
            doubles.append(c.y)

        cgf = CurvedGeometryFactory(tolerance)
        _CircularRing.__init__(self, doubles, cgf, tolerance)


geom._enhance(CircularRing)
core.registerTypeMapping(_CircularRing, CircularRing)
class MultiPoint(_MultiPoint):
    """
  A MultiPoint goemetry.

  *points* is a variable number of ``list``/``tuple`` arguments. 

  >>> MultiPoint([1,2], [3,4])
  MULTIPOINT ((1 2), (3 4))

  *points* may also be specified as a variable number of :class:`Point` arguments. 

  >>> MultiPoint(Point(1,2), Point(3,4))
  MULTIPOINT ((1 2), (3 4))
   
  """

    def __init__(self, *points):

        if isinstance(points[0], _MultiPoint):
            mp = points[0]
            points = [mp.getGeometryN(i) for i in range(mp.numGeometries)]
        elif isinstance(points[0], (list, tuple)):
            points = [Point(*p) for p in points]

        _MultiPoint.__init__(self, points, geom._factory)


geom._enhance(MultiPoint)
core.registerTypeMapping(_MultiPoint, MultiPoint)
Exemple #32
0
from org.locationtech.jts.geom import Coordinate
from org.locationtech.jts.geom import Point as _Point
from geoscript import core
import geom


class Point(_Point):
    """
  A Point geometry.

  *coord* is a variable list of x, y, z arguments.

  >>> Point(1,2)
  POINT (1 2)
  """
    def __init__(self, *coord):

        if len(coord) == 1 and isinstance(coord[0], _Point):
            p = coord[0]
        else:
            c = Coordinate(coord[0], coord[1])
            if len(coord) > 2:
                c.z = coord[2]
            p = geom._factory.createPoint(c)

        _Point.__init__(self, p.coordinateSequence, geom._factory)


geom._enhance(Point)
core.registerTypeMapping(_Point, Point)
from org.geotools.geometry.jts import CurvedGeometryFactory
from linestring import LineString
from circularstring import CircularString
from java.lang import Double
from geoscript import core
import geom


class CompoundCurve(_CompoundCurve):
    """
    A CompoundCurve geometry.

    *linestrings* is a variable list of ``LineStrings`` or ``CircularStrings`` arguments.

    >>> CompoundCurve(CircularString([10.0, 10.0], [0.0, 20.0], [-10.0, 10.0]), LineString([-10.0, 10.0], [-10.0, 0.0], [10.0, 0.0], [5.0, 5.0]))
    COMPOUNDCURVE (CIRCULARSTRING (10.0 10.0, 0.0 20.0, -10.0 10.0), (-10.0 10.0, -10.0 0.0, 10.0 0.0, 5.0 5.0))
    """
    def __init__(self, *linestrings):
        tolerance = Double.MAX_VALUE
        if len(linestrings) == 1 and isinstance(linestrings[0],
                                                _CompoundCurve):
            cc = linestrings[0]
            linestrings = cc.components

        cgf = CurvedGeometryFactory(tolerance)
        _CompoundCurve.__init__(self, linestrings, cgf, tolerance)


geom._enhance(CompoundCurve)
core.registerTypeMapping(_CompoundCurve, CompoundCurve)