Python ee.Geometry() Examples

The following are 30 code examples of ee.Geometry(). 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 ee , or try the search function .
Example #1
Source File: map.py    From ipygee with MIT License 7 votes vote down vote up
def addMarker(self, marker, visParams=None, name=None, show=True,
                  opacity=None, replace=True,
                  inspect={'data':None, 'reducer':None, 'scale':None}):
        """ General method to add Geometries, Features or FeatureCollections
        as Markers """

        if isinstance(marker, ee.Geometry):
            self.addGeometry(marker, visParams, name, show, opacity, replace,
                             inspect)

        elif isinstance(marker, ee.Feature):
            self.addFeature(marker, visParams, name, show, opacity, replace,
                            inspect)

        elif isinstance(marker, ee.FeatureCollection):
            geometry = marker.geometry()
            self.addGeometry(marker, visParams, name, show, opacity, replace,
                             inspect) 
Example #2
Source File: dispatcher.py    From ipygee with MIT License 6 votes vote down vote up
def geometry(info):
    """ Dispatch a ee.Geometry """
    coords = info.get('coordinates')
    typee = info.get('type')
    widget = Accordion()

    if typee in ['MultiPoint', 'MultiPolygon', 'MultiLineString']:
        inner_children = []
        for coord in coords:
            inner_children.append(Label(str(coord)))
        inner_acc = Accordion(inner_children)
        inner_acc.selected_index = None # this will unselect all
        for i, _ in enumerate(coords):
            inner_acc.set_title(i, str(i))
        children = [inner_acc]
    else:
        children = [Label(str(coords))]

    widget.children = children
    widget.set_title(0, 'coordinates')
    widget.selected_index = None
    return widget 
Example #3
Source File: geometry_test.py    From aqua-monitor with GNU Lesser General Public License v3.0 6 votes vote down vote up
def assertInvalid(self, ctor, msg, *coords):
    """Verifies that geometry is invalid.

    Calls the given constructor with whatever arguments have been passed,
    and verifies that the given error message is thrown.

    Args:
      ctor: The geometry constructor function, e.g. ee.Geometry.MultiPoint.
      msg: The expected error message in the thrown exception.
      *coords: The coordinates of the geometry.
    """
    try:
      ctor(*coords)
    except ee.EEException as e:
      self.assertTrue(msg in str(e))
    else:
      self.fail('Expected an exception.') 
Example #4
Source File: test_d_collection.py    From openet-ssebop-beta with Apache License 2.0 6 votes vote down vote up
def test_Collection_init_cloud_cover_exception():
    """Test if Exception is raised for an invalid cloud_cover_max"""
    with pytest.raises(TypeError):
        default_coll_obj(cloud_cover_max='A')
    with pytest.raises(ValueError):
        default_coll_obj(cloud_cover_max=-1)
    with pytest.raises(ValueError):
        default_coll_obj(cloud_cover_max=101)


# # TODO: Test for Error if geometry is not ee.Geometry
# def test_Collection_init_geometry_exception():
#     """Test if Exception is raised for an invalid geometry"""
#     args = default_coll_args()
#     args['geometry'] = 'DEADBEEF'
#     s = ssebop.Collection(**args)
#     assert utils.getinfo(s.geometry) ==


# TODO: Test if a geojson string can be passed for the geometry
# def test_Collection_init_geometry_geojson():
#     assert False 
Example #5
Source File: geometry_test.py    From earthengine with MIT License 6 votes vote down vote up
def assertInvalid(self, ctor, msg, *coords):
    """Verifies that geometry is invalid.

    Calls the given constructor with whatever arguments have been passed,
    and verifies that the given error message is thrown.

    Args:
      ctor: The geometry constructor function, e.g. ee.Geometry.MultiPoint.
      msg: The expected error message in the thrown exception.
      *coords: The coordinates of the geometry.
    """
    try:
      ctor(*coords)
    except ee.EEException as e:
      self.assertTrue(msg in str(e))
    else:
      self.fail('Expected an exception.') 
Example #6
Source File: map.py    From ipygee with MIT License 6 votes vote down vote up
def centerObject(self, eeObject, zoom=None, method=1):
        """ Center an eeObject

        :param eeObject:
        :param zoom:
        :param method: experimetal methods to estimate zoom for fitting bounds
            Currently: 1 or 2
        :type: int
        """
        bounds = getBounds(eeObject)
        if bounds:
            try:
                inverse = inverseCoordinates(bounds)
                centroid = ee.Geometry.Polygon(inverse) \
                    .centroid().getInfo()['coordinates']
            except:
                centroid = [0, 0]

            self.center = inverseCoordinates(centroid)
            if zoom:
                self.zoom = zoom
            else:
                self.zoom = getZoom(bounds, method) 
Example #7
Source File: scores.py    From geebap with GNU General Public License v3.0 6 votes vote down vote up
def map(self, collection, **kwargs):
        """ Map the score over a collection

        :param col: collection
        :type col: satcol.Collection
        :param geom: boundaries geometry
        :type geom: ee.Geometry or ee.Feature
        """
        col = kwargs.get('col')
        geom = kwargs.get('geom')
        minscale = min([band.scale for band in col.bands])
        def wrap(img):
            score = self.compute(img, geometry=geom, scale=minscale,
                                 count_zeros=self.count_zeros)
            prop = score.get(self.name)
            return img.addBands(score).set(self.name, prop)

        return collection.map(wrap) 
Example #8
Source File: maptools.py    From ipygee with MIT License 6 votes vote down vote up
def getBounds(eeObject):
    if isinstance(eeObject, list):
        bounds = eeObject
    else:
        # Make a buffer if object is a Point
        if isinstance(eeObject, ee.Geometry):
            t = eeObject.type().getInfo()
            if t == 'Point':
                eeObject = eeObject.buffer(1000)

        bounds = tools.geometry.getRegion(eeObject, True)

    # Catch unbounded images
    unbounded = [[[-180.0, -90.0], [180.0, -90.0],
                  [180.0, 90.0], [-180.0, 90.0],
                  [-180.0, -90.0]]]

    if bounds == unbounded:
        print("can't center object because it is unbounded")
        return None

    bounds = inverseCoordinates(bounds)
    return bounds 
Example #9
Source File: test_d_collection.py    From openet-ssebop-beta with Apache License 2.0 5 votes vote down vote up
def test_Collection_interpolate_only_interpolate_images():
    """Test if count band is returned if no images in the date range"""
    variables = {'et', 'count'}
    output = utils.getinfo(default_coll_obj(
        collections=['LANDSAT/LC08/C01/T1_RT_TOA'],
        geometry=ee.Geometry.Point(-123.623, 44.745),
        start_date='2017-04-01', end_date='2017-04-30',
        variables=list(variables), cloud_cover_max=70).interpolate())
    assert {y['id'] for x in output['features'] for y in x['bands']} == variables 
Example #10
Source File: test_d_collection.py    From openet-ssebop-beta with Apache License 2.0 5 votes vote down vote up
def test_Collection_build_filter_args():
    # Need to test with two collections to catch bug when deepcopy isn't used
    collections = ['LANDSAT/LC08/C01/T1_SR', 'LANDSAT/LE07/C01/T1_SR']
    wrs2_filter = [
        {'type': 'equals', 'leftField': 'WRS_PATH', 'rightValue': 44},
        {'type': 'equals', 'leftField': 'WRS_ROW', 'rightValue': 33}]
    coll_obj = default_coll_obj(
        collections=collections,
        geometry=ee.Geometry.Rectangle(-125, 35, -120, 40),
        filter_args={c: wrs2_filter for c in collections})
    output = utils.getinfo(coll_obj._build(variables=['et']))
    assert {x[5:11] for x in parse_scene_id(output)} == {'044033'} 
Example #11
Source File: test_d_collection.py    From openet-ssebop-beta with Apache License 2.0 5 votes vote down vote up
def test_Collection_build_filter_dates_lc08():
    """Test that pre-op Landsat 8 images before 2013-03-24 are filtered.

    We may want to move this date back to 2013-04-01.
    """
    output = utils.getinfo(default_coll_obj(
        collections=['LANDSAT/LC08/C01/T1_TOA'],
        start_date='2013-01-01', end_date='2013-05-01',
        geometry=ee.Geometry.Rectangle(-125, 25, -65, 50))._build(variables=['ndvi']))
    assert not [x for x in parse_scene_id(output) if x.split('_')[-1] < '20130324']
    # assert parse_scene_id(output) == [] 
Example #12
Source File: test_d_collection.py    From openet-ssebop-beta with Apache License 2.0 5 votes vote down vote up
def test_Collection_build_filter_dates_lt05():
    """Test that bad Landsat 5 in 2012 images are filtered"""
    output = utils.getinfo(default_coll_obj(
        collections=['LANDSAT/LT05/C01/T1_TOA'],
        start_date='2012-01-01', end_date='2013-01-01',
        geometry=ee.Geometry.Rectangle(-125, 25, -65, 50))._build(variables=['ndvi']))
    assert parse_scene_id(output) == [] 
Example #13
Source File: geometry_test.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def testValid_LineString(self):
    """Verifies LineString constructor behavior with valid arguments."""
    self.assertValid(2, ee.Geometry.LineString, 1, 2, 3, 4, 5, 6) 
Example #14
Source File: imagecollection.py    From gee_tools with MIT License 5 votes vote down vote up
def mergeGeometries(collection):
    """ Merge the geometries of many images. Return ee.Geometry """
    imlist = collection.toList(collection.size())

    first = ee.Image(imlist.get(0))
    rest = imlist.slice(1)

    def wrap(img, ini):
        ini = ee.Geometry(ini)
        img = ee.Image(img)
        geom = img.geometry()
        union = geom.union(ini)
        return union.dissolve()

    return ee.Geometry(rest.iterate(wrap, first.geometry())) 
Example #15
Source File: geometry_test.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def testComputedCoordinate(self):
    """Verifies that a computed coordinate produces a computed geometry."""
    coords = [1, ee.Number(1).add(1)]
    p = ee.Geometry.Point(coords)

    self.assertTrue(isinstance(p, ee.Geometry))
    self.assertEquals(
        ee.ApiFunction.lookup('GeometryConstructors.Point'), p.func)
    self.assertEquals({'coordinates': ee.List(coords)}, p.args) 
Example #16
Source File: geometry_test.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def testComputedGeometries(self):
    """Verifies the computed object behavior of the Geometry constructor."""
    line = ee.Geometry.LineString(1, 2, 3, 4)
    bounds = line.bounds()

    self.assertTrue(isinstance(bounds, ee.Geometry))
    self.assertEquals(
        ee.ApiFunction.lookup('Geometry.bounds'), bounds.func)
    self.assertEquals(line, bounds.args['geometry'])
    self.assertTrue(hasattr(bounds, 'bounds')) 
Example #17
Source File: geometry_test.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def testGeodesicFlag(self):
    """Verifies that JSON parsing and generation preserves the geodesic flag."""
    geodesic = ee.Geometry({
        'type': 'LineString',
        'coordinates': [[1, 2], [3, 4]],
        'geodesic': True
    })
    projected = ee.Geometry({
        'type': 'LineString',
        'coordinates': [[1, 2], [3, 4]],
        'geodesic': False
    })
    self.assertTrue(geodesic.toGeoJSON()['geodesic'])
    self.assertFalse(projected.toGeoJSON()['geodesic']) 
Example #18
Source File: geometry_test.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def testArrayConstructors(self):
    """Verifies that constructors that take arrays fix nesting."""
    get_coordinates_count = lambda g: len(g.toGeoJSON()['coordinates'])

    point = ee.Geometry.Point([1, 2])
    self.assertEquals(2, get_coordinates_count(point))

    multipoint = ee.Geometry.MultiPoint([[1, 2], [3, 4], [5, 6]])
    self.assertEquals(3, get_coordinates_count(multipoint))

    line = ee.Geometry.LineString([[1, 2], [3, 4], [5, 6]])
    self.assertEquals(3, get_coordinates_count(line))

    ring = ee.Geometry.LinearRing([[1, 2], [3, 4], [5, 6]])
    self.assertEquals(3, get_coordinates_count(ring))

    multiline = ee.Geometry.MultiLineString(
        [[[1, 2], [3, 4]],
         [[5, 6], [7, 8]]])
    self.assertEquals(2, get_coordinates_count(multiline))

    polygon = ee.Geometry.Polygon([[[1, 2], [3, 4], [5, 6]]])
    self.assertEquals(1, get_coordinates_count(polygon))

    mpolygon = ee.Geometry.MultiPolygon(
        [[[[1, 2], [3, 4], [5, 6]]],
         [[[1, 2], [3, 4], [5, 6]]]])
    self.assertEquals(2, get_coordinates_count(mpolygon)) 
Example #19
Source File: image.py    From gee_tools with MIT License 5 votes vote down vote up
def renameDict(image, names):
    """ Renames bands of images using a dict

    :param names: matching names where key is original name and values the
        new name
    :type names: dict
    :rtype: ee.Image

    :EXAMPLE:

    .. code:: python

        image = ee.Image("LANDSAT/LC8_L1T_TOA_FMASK/LC82310902013344LGN00")
        p = ee.Geometry.Point(-71.72029495239258, -42.78997046797438)

        i = rename_bands({"B1":"BLUE", "B2":"GREEN"})

        print get_value(image, p)
        print get_value(i, p)

    >> {u'B1': 0.10094200074672699, u'B2': 0.07873955368995667, u'B3': 0.057160500437021255}
    >> {u'BLUE': 0.10094200074672699, u'GREEN': 0.07873955368995667, u'B3': 0.057160500437021255}
    """
    bandnames = image.bandNames()
    newnames = ee_list.replaceDict(bandnames, names)
    return image.select(bandnames, newnames) 
Example #20
Source File: geometry_test.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def testEvenOddPolygon(self):
    poly1 = ee.Geometry.Polygon([0, 0, 0, 5, 5, 0])
    self.assertTrue(poly1.toGeoJSON()['evenOdd'])
    poly2 = ee.Geometry.Polygon([0, 0, 0, 5, 5, 0], None, None, None, False)
    self.assertFalse(poly2.toGeoJSON()['evenOdd']) 
Example #21
Source File: geometry_test.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def testInvalid_MultiPolygon(self):
    """Verifies MultiPolygon constructor behavior with invalid arguments."""
    f = ee.Geometry.MultiPolygon
    self.assertInvalid(f, 'Invalid number of coordinates: 5', 1, 2, 3, 4, 5)
    self.assertInvalid(f, 'Invalid number of coordinates: 5', [1, 2, 3, 4, 5])
    self.assertInvalid(f, 'Invalid geometry', [[1, 2], [3, 4], 5])
    # Too many nesting levels.
    self.assertInvalid(f, 'Invalid geometry', [[[[[1, 2], [3, 4], [5, 6]]]]])
    # Bad nesting
    self.assertInvalid(f, 'Invalid geometry', [[[[1, 2], [3, 4]], [1, 2]]]) 
Example #22
Source File: geometry_test.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def testInvalid_Polygon(self):
    """Verifies Polygon constructor behavior with invalid arguments."""
    f = ee.Geometry.Polygon
    self.assertInvalid(
        f, 'Invalid number of coordinates: 5', 1, 2, 3, 4, 5)
    self.assertInvalid(f, 'Invalid number of coordinates: 5', [1, 2, 3, 4, 5])
    self.assertInvalid(f, 'Invalid geometry', [[1, 2], [3, 4], 5])
    # Too many nesting levels.
    self.assertInvalid(f, 'Invalid geometry', [[[[1, 2], [3, 4], [5, 6]]]])
    # Bad nesting
    self.assertInvalid(f, 'Invalid geometry', [[[1, 2], [3, 4]], [1, 2]]) 
Example #23
Source File: geometry_test.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def testInvalid_LinearRing(self):
    """Verifies LinearRing constructor behavior with invalid arguments."""
    f = ee.Geometry.LinearRing
    self.assertInvalid(
        f, 'Invalid number of coordinates: 5', 1, 2, 3, 4, 5)
    self.assertInvalid(f, 'Invalid number of coordinates: 5', [1, 2, 3, 4, 5])
    self.assertInvalid(f, 'Invalid geometry', [[1, 2], [3, 4], 5])
    # Too many nesting levels.
    self.assertInvalid(f, 'Invalid geometry', [[[1, 2], [3, 4]]]) 
Example #24
Source File: geometry_test.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def testInvalid_LineString(self):
    """Verifies LineString constructor behavior with invalid arguments."""
    f = ee.Geometry.LineString
    self.assertInvalid(
        f, 'Invalid number of coordinates: 5', 1, 2, 3, 4, 5)
    self.assertInvalid(f, 'Invalid number of coordinates: 5', [1, 2, 3, 4, 5])
    self.assertInvalid(f, 'Invalid geometry', [[1, 2], [3, 4], 5])
    # Too many nesting levels.
    self.assertInvalid(f, 'Invalid geometry', [[[1, 2], [3, 4]]]) 
Example #25
Source File: geometry_test.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def testInvalid_MultiPoint(self):
    """Verifies MultiPoint constructor behavior with invalid arguments."""
    f = ee.Geometry.MultiPoint
    self.assertInvalid(
        f, 'Invalid number of coordinates: 5', 1, 2, 3, 4, 5)
    self.assertInvalid(f, 'Invalid number of coordinates: 5', [1, 2, 3, 4, 5])
    self.assertInvalid(f, 'Invalid geometry', [[1, 2], [3, 4], 5])
    # Too many nesting levels.
    self.assertInvalid(f, 'Invalid geometry', [[[1, 2], [3, 4]]]) 
Example #26
Source File: geometry_test.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def testValid_MultiPolygon(self):
    """Verifies MultiPolygon constructor behavior with valid arguments."""
    self.assertValid(4, ee.Geometry.MultiPolygon, 1, 2, 3, 4, 5, 6)
    self.assertValid(1, ee.Geometry.MultiPolygon) 
Example #27
Source File: geometry_test.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def testValid_Rectangle(self):
    """Verifies Rectangle constructor behavior with valid arguments."""
    self.assertValid(3, ee.Geometry.Rectangle, 1, 2, 5, 6) 
Example #28
Source File: geometry_test.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def testValid_MultiLineString(self):
    """Verifies MultiLineString constructor behavior with valid arguments."""
    self.assertValid(3, ee.Geometry.MultiLineString, 1, 2, 3, 4, 5, 6)
    self.assertValid(1, ee.Geometry.MultiLineString) 
Example #29
Source File: geometry_test.py    From aqua-monitor with GNU Lesser General Public License v3.0 5 votes vote down vote up
def testValid_LinearRing(self):
    """Verifies LinearRing constructor behavior with valid arguments."""
    self.assertValid(2, ee.Geometry.LinearRing, 1, 2, 3, 4, 5, 6) 
Example #30
Source File: dispatcher.py    From ipygee with MIT License 5 votes vote down vote up
def feature(info):
    """ Dispatch a ee.Feature """
    geom = info.get('geometry')
    geomtype = geom.get('type')
    props = info.get('properties')

    # Contruct an accordion with the geometries
    acc = geometry(geom)
    children = list(acc.children)

    # Properties
    if props:
        # dispatch properties
        prop_acc = dispatch(props)
    else:
        prop_acc = dispatch('Feature has no properties')

    # Append properties as a child
    children.append(prop_acc.widget)
    acc.set_title(1, 'properties')
    acc.children = children
    acc.selected_index = None

    # Geometry Type
    typewid = dispatch(geomtype)


    return acc