collection.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. #!/usr/bin/env python
  2. """Common representation for ImageCollection and FeatureCollection.
  3. This class is never intended to be instantiated by the user.
  4. """
  5. # Using lowercase function naming to match the JavaScript names.
  6. # pylint: disable=g-bad-name
  7. from . import apifunction
  8. from . import deprecation
  9. from . import ee_exception
  10. from . import element
  11. from . import filter # pylint: disable=redefined-builtin
  12. class Collection(element.Element):
  13. """Base class for ImageCollection and FeatureCollection."""
  14. _initialized = False
  15. def __init__(self, func, args, opt_varName=None):
  16. """Constructs a collection by initializing its ComputedObject."""
  17. super(Collection, self).__init__(func, args, opt_varName)
  18. @classmethod
  19. def initialize(cls):
  20. """Imports API functions to this class."""
  21. if not cls._initialized:
  22. apifunction.ApiFunction.importApi(cls, 'Collection', 'Collection')
  23. apifunction.ApiFunction.importApi(
  24. cls, 'AggregateFeatureCollection', 'Collection', 'aggregate_')
  25. cls._initialized = True
  26. @classmethod
  27. def reset(cls):
  28. """Removes imported API functions from this class.
  29. Also resets the serial ID used for mapping Python functions to 0.
  30. """
  31. apifunction.ApiFunction.clearApi(cls)
  32. cls._initialized = False
  33. def filter(self, new_filter):
  34. """Apply a filter to this collection.
  35. Args:
  36. new_filter: Filter to add to this collection.
  37. Returns:
  38. The filtered collection object.
  39. """
  40. if not new_filter:
  41. raise ee_exception.EEException('Empty filters.')
  42. return self._cast(apifunction.ApiFunction.call_(
  43. 'Collection.filter', self, new_filter))
  44. @deprecation.CanUseDeprecated
  45. def filterMetadata(self, name, operator, value):
  46. """Shortcut to add a metadata filter to a collection.
  47. This is equivalent to self.filter(Filter().metadata(...)).
  48. Args:
  49. name: Name of a property to filter.
  50. operator: Name of a comparison operator as defined
  51. by FilterCollection. Possible values are: "equals", "less_than",
  52. "greater_than", "not_equals", "not_less_than", "not_greater_than",
  53. "starts_with", "ends_with", "not_starts_with", "not_ends_with",
  54. "contains", "not_contains".
  55. value: The value to compare against.
  56. Returns:
  57. The filtered collection.
  58. """
  59. return self.filter(filter.Filter.metadata_(name, operator, value))
  60. def filterBounds(self, geometry):
  61. """Shortcut to add a geometry filter to a collection.
  62. Items in the collection with a footprint that fails to intersect
  63. the given geometry will be excluded.
  64. This is equivalent to self.filter(Filter().geometry(...)).
  65. Caution: providing a large or complex collection as the `geometry` argument
  66. can result in poor performance. Collating the geometry of collections does
  67. not scale well; use the smallest collection (or geometry) that is required
  68. to achieve the desired outcome.
  69. Args:
  70. geometry: The boundary to filter to either as a GeoJSON geometry,
  71. or a FeatureCollection, from which a geometry will be extracted.
  72. Returns:
  73. The filtered collection.
  74. """
  75. return self.filter(filter.Filter.geometry(geometry))
  76. def filterDate(self, start, opt_end=None):
  77. """Shortcut to filter a collection with a date range.
  78. Items in the collection with a system:time_start property that doesn't
  79. fall between the start and end dates will be excluded.
  80. This is equivalent to self.filter(ee.Filter.date(...)); see the ee.Filter
  81. type for other date filtering options.
  82. Args:
  83. start: The start date as a Date object, a string representation of
  84. a date, or milliseconds since epoch.
  85. opt_end: The end date as a Date object, a string representation of
  86. a date, or milliseconds since epoch.
  87. Returns:
  88. The filter object.
  89. """
  90. return self.filter(filter.Filter.date(start, opt_end))
  91. def getInfo(self):
  92. """Returns all the known information about this collection.
  93. This function makes an REST call to to retrieve all the known information
  94. about this collection.
  95. Returns:
  96. The return contents vary but will include at least:
  97. features: an array containing metadata about the items in the
  98. collection that passed all filters.
  99. properties: a dictionary containing the collection's metadata
  100. properties.
  101. """
  102. return super(Collection, self).getInfo()
  103. def limit(self, maximum, opt_property=None, opt_ascending=None):
  104. """Limit a collection to the specified number of elements.
  105. This limits a collection to the specified number of elements, optionally
  106. sorting them by a specified property first.
  107. Args:
  108. maximum: The number to limit the collection to.
  109. opt_property: The property to sort by, if sorting.
  110. opt_ascending: Whether to sort in ascending or descending order.
  111. The default is true (ascending).
  112. Returns:
  113. The collection.
  114. """
  115. args = {'collection': self, 'limit': maximum}
  116. if opt_property is not None:
  117. args['key'] = opt_property
  118. if opt_ascending is not None:
  119. args['ascending'] = opt_ascending
  120. return self._cast(
  121. apifunction.ApiFunction.apply_('Collection.limit', args))
  122. def sort(self, prop, opt_ascending=None):
  123. """Sort a collection by the specified property.
  124. Args:
  125. prop: The property to sort by.
  126. opt_ascending: Whether to sort in ascending or descending
  127. order. The default is true (ascending).
  128. Returns:
  129. The collection.
  130. """
  131. args = {'collection': self, 'key': prop}
  132. if opt_ascending is not None:
  133. args['ascending'] = opt_ascending
  134. return self._cast(
  135. apifunction.ApiFunction.apply_('Collection.limit', args))
  136. @staticmethod
  137. def name():
  138. return 'Collection'
  139. @staticmethod
  140. def elementType():
  141. """Returns the type of the collection's elements."""
  142. return element.Element
  143. def map(self, algorithm, opt_dropNulls=None):
  144. """Maps an algorithm over a collection.
  145. Args:
  146. algorithm: The operation to map over the images or features of the
  147. collection, a Python function that receives an image or features and
  148. returns one. The function is called only once and the result is
  149. captured as a description, so it cannot perform imperative operations
  150. or rely on external state.
  151. opt_dropNulls: If true, the mapped algorithm is allowed to return nulls,
  152. and the elements for which it returns nulls will be dropped.
  153. Returns:
  154. The mapped collection.
  155. Raises:
  156. ee_exception.EEException: if algorithm is not a function.
  157. """
  158. element_type = self.elementType()
  159. with_cast = lambda e: algorithm(element_type(e))
  160. return self._cast(apifunction.ApiFunction.call_(
  161. 'Collection.map', self, with_cast, opt_dropNulls))
  162. def iterate(self, algorithm, first=None):
  163. """Iterates over a collection with an algorithm.
  164. Applies a user-supplied function to each element of a collection. The
  165. user-supplied function is given two arguments: the current element, and
  166. the value returned by the previous call to iterate() or the first argument,
  167. for the first iteration. The result is the value returned by the final
  168. call to the user-supplied function.
  169. Args:
  170. algorithm: The function to apply to each element. Must take two
  171. arguments - an element of the collection and the value from the
  172. previous iteration.
  173. first: The initial state.
  174. Returns:
  175. The result of the Collection.iterate() call.
  176. Raises:
  177. ee_exception.EEException: if algorithm is not a function.
  178. """
  179. element_type = self.elementType()
  180. with_cast = lambda e, prev: algorithm(element_type(e), prev)
  181. return apifunction.ApiFunction.call_(
  182. 'Collection.iterate', self, with_cast, first)