RadGEEToolbox 1.7.2__py3-none-any.whl → 1.7.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  import ee
2
+ import warnings
2
3
 
3
-
4
- def CollectionStitch(img_col1, img_col2, copy_properties_from=1):
4
+ def collectionStitch(img_col1, img_col2, copy_properties_from=1):
5
5
  """
6
6
  Function to mosaic two RadGEETools image collection objects which share image dates.
7
7
  Mosaics are only formed for dates where both image collections have images. Server-side friendly.
@@ -42,8 +42,14 @@ def CollectionStitch(img_col1, img_col2, copy_properties_from=1):
42
42
  new_col = ee.ImageCollection.fromImages(image_list)
43
43
  return new_col
44
44
 
45
+ def CollectionStitch(img_col1, img_col2, copy_properties_from=1):
46
+ warnings.warn(
47
+ "CollectionStitch is deprecated. Please use collectionStitch instead.",
48
+ DeprecationWarning,
49
+ stacklevel=2)
50
+ return collectionStitch(img_col1, img_col2, copy_properties_from)
45
51
 
46
- def MosaicByDate(img_col):
52
+ def mosaicByDate(img_col):
47
53
  """
48
54
  Function to mosaic collection images that share the same date. Server-side friendly. Requires images to have date property of "Date_Filter"
49
55
 
@@ -80,3 +86,10 @@ def MosaicByDate(img_col):
80
86
 
81
87
  # Convert the list of mosaics to an ImageCollection
82
88
  return new_col
89
+
90
+ def MosaicByDate(img_col):
91
+ warnings.warn(
92
+ "MosaicByDate is deprecated. Please use mosaicByDate instead.",
93
+ DeprecationWarning,
94
+ stacklevel=2)
95
+ return mosaicByDate(img_col)
@@ -0,0 +1,249 @@
1
+ import ee
2
+
3
+ class ExportToDrive:
4
+ """
5
+ A class to handle exporting Earth Engine images and image collections to Google Drive.
6
+
7
+ This class supports exporting both native Earth Engine objects (ee.Image, ee.ImageCollection)
8
+ and RadGEEToolbox objects (e.g., LandsatCollection, Sentinel2Collection).
9
+
10
+ It is designed to intelligently handle RadGEEToolbox collections by utilizing their cached
11
+ `.dates` property for naming files, ensuring readable filenames (e.g., 'MyExport_2023-06-01')
12
+ instead of long system IDs.
13
+
14
+ IMPORTANT: After creating an instance of this class, you must call the `export()` method
15
+ to initiate the export process.
16
+
17
+ For example, to export a RadGEEToolbox collection:
18
+ ```python
19
+ collection = LandsatCollection(...) # Assume this is a RadGEEToolbox object
20
+ exporter = ExportToDrive(
21
+ input_data=collection,
22
+ description="Landsat_Export",
23
+ folder="GEE_Exports",
24
+ scale=30,
25
+ name_pattern="{date}",
26
+ )
27
+ exporter.export()
28
+ ```
29
+
30
+ Args:
31
+ input_data (ee.Image, ee.ImageCollection, or RadGEEToolbox object): The data to export.
32
+ Can be a single image, a collection, or a RadGEEToolbox wrapper object.
33
+ description (str): A description of the export task. This serves as the task name in the
34
+ GEE code editor and the default prefix for filenames. Defaults to 'export'.
35
+ folder (str, optional): The name of the destination folder in Google Drive. Defaults to None (root).
36
+ fileNamePrefix (str, optional): The filename prefix. For collections, this is prepended
37
+ to the generated unique name. If None, it defaults to the `description`.
38
+ scale (int): The resolution in meters per pixel. Defaults to 30.
39
+ region (ee.Geometry, optional): The region/geometry to export. Defaults to None (uses image footprint).
40
+ crs (str, optional): The coordinate reference system (e.g., 'EPSG:4326'). Defaults to None (uses image CRS).
41
+ maxPixels (int, optional): The maximum number of pixels allowed in the export. Defaults to 1e13.
42
+ fileFormat (str, optional): The output file format (e.g., 'GeoTIFF', 'TFRecord'). Defaults to 'GeoTIFF'.
43
+ name_pattern (str, optional): A string pattern for naming files when exporting a collection.
44
+ Supported placeholders:
45
+ - {date}: The date of the image. Prioritizes the RadGEEToolbox cached '.dates' list,
46
+ then 'Date_Filter' property, then formatted 'system:time_start'.
47
+ - {id}: The system:index of the image.
48
+ Defaults to '{date}'. The final filename will generally be "{fileNamePrefix}_{name_pattern}".
49
+ date_pattern (str, optional): The date format string to use if falling back to 'system:time_start'
50
+ (e.g., 'YYYY-MM-dd'). Defaults to 'YYYY-MM-dd'.
51
+ **kwargs: Additional keyword arguments passed directly to ee.batch.Export.image.toDrive
52
+ (e.g., 'formatOptions', 'shardSize').
53
+
54
+ Raises:
55
+ ValueError: If the input data type is not supported or if required arguments (like scale) are missing/invalid.
56
+ """
57
+
58
+ def __init__(
59
+ self,
60
+ input_data,
61
+ description="export",
62
+ folder=None,
63
+ fileNamePrefix=None,
64
+ scale=30,
65
+ region=None,
66
+ crs=None,
67
+ maxPixels=1e13,
68
+ fileFormat="GeoTIFF",
69
+ name_pattern="{date}",
70
+ date_pattern="YYYY-MM-dd",
71
+ **kwargs
72
+ ):
73
+ # 1. Capture RadGEEToolbox Metadata BEFORE unwrapping
74
+ # We explicitly look for the cached .dates list which is standard in RadGEEToolbox collections
75
+ self.radgee_dates = getattr(input_data, "dates", None)
76
+
77
+ # 2. Input Processing & Conversion
78
+ self.ee_object = self._validate_and_convert_input(input_data)
79
+
80
+ # Determine strict type of the resulting EE object
81
+ self.is_collection = isinstance(self.ee_object, ee.ImageCollection)
82
+ self.is_image = isinstance(self.ee_object, ee.Image)
83
+
84
+ if not self.is_collection and not self.is_image:
85
+ raise ValueError(
86
+ "Processed input must be an ee.Image or ee.ImageCollection. "
87
+ f"Got type: {type(self.ee_object)}"
88
+ )
89
+
90
+ # 3. Argument Validation
91
+ if scale is None:
92
+ raise ValueError("The 'scale' argument is required for export.")
93
+
94
+ if description is None or not isinstance(description, str):
95
+ raise ValueError("The 'description' argument must be a valid string.")
96
+
97
+ # Check for extraneous collection arguments when exporting a single image
98
+ if self.is_image:
99
+ if name_pattern != "{date}" or date_pattern != "YYYY-MM-dd":
100
+ print(
101
+ "Info: Extra arguments 'name_pattern' and/or 'date_pattern' were provided "
102
+ "but will be ignored because the input is a single image."
103
+ )
104
+
105
+ # 4. Store Attributes
106
+ self.description = description
107
+ self.folder = folder
108
+ self.fileNamePrefix = fileNamePrefix if fileNamePrefix else description
109
+ self.scale = scale
110
+ self.region = region
111
+ self.crs = crs
112
+ self.maxPixels = maxPixels
113
+ self.fileFormat = fileFormat
114
+ self.name_pattern = name_pattern
115
+ self.date_pattern = date_pattern
116
+ self.extra_kwargs = kwargs
117
+
118
+ def _validate_and_convert_input(self, input_data):
119
+ """
120
+ Helper to unwrap RadGEEToolbox objects or verify EE objects.
121
+ """
122
+ # Check if it's a RadGEEToolbox object (duck typing checks for 'collection' attribute)
123
+ if hasattr(input_data, "collection") and isinstance(input_data.collection, ee.ImageCollection):
124
+ return input_data.collection
125
+
126
+ # Check if it is already a valid EE object
127
+ if isinstance(input_data, (ee.Image, ee.ImageCollection)):
128
+ return input_data
129
+
130
+ # Attempt to handle computed objects that are implicitly images
131
+ try:
132
+ return ee.Image(input_data)
133
+ except Exception:
134
+ pass
135
+
136
+ raise ValueError(
137
+ "Input data is not a recognized RadGEEToolbox object, ee.Image, or ee.ImageCollection."
138
+ )
139
+
140
+ def export(self):
141
+ """
142
+ Initiates the export process. Detects whether to run a single task
143
+ or iterate through a collection.
144
+ """
145
+ if self.is_image:
146
+ self._export_single_image()
147
+ elif self.is_collection:
148
+ self._export_collection()
149
+
150
+ def _export_single_image(self):
151
+ """Internal method to export a single image."""
152
+ print(f"Starting export task for single image: {self.description}")
153
+
154
+ # Construct parameters dict, filtering out None values
155
+ params = {
156
+ "image": self.ee_object,
157
+ "description": self.description,
158
+ "folder": self.folder,
159
+ "fileNamePrefix": self.fileNamePrefix,
160
+ "scale": self.scale,
161
+ "region": self.region,
162
+ "crs": self.crs,
163
+ "maxPixels": self.maxPixels,
164
+ "fileFormat": self.fileFormat,
165
+ }
166
+ # Merge basic params with any extra kwargs provided
167
+ params.update(self.extra_kwargs)
168
+ # Remove keys with None values to allow GEE defaults to take over
169
+ params = {k: v for k, v in params.items() if v is not None}
170
+
171
+ task = ee.batch.Export.image.toDrive(**params)
172
+ task.start()
173
+ print(f"Task ID: {task.id}")
174
+
175
+ def _export_collection(self):
176
+ """Internal method to iterate and export a collection."""
177
+ # Get the size of the collection locally
178
+ try:
179
+ count = self.ee_object.size().getInfo()
180
+ except Exception as e:
181
+ raise ValueError(f"Could not determine collection size. Error: {e}")
182
+
183
+ if count == 0:
184
+ print("The image collection is empty. No export tasks were started.")
185
+ return
186
+
187
+ print(f"Processing collection export... ({count} images found)")
188
+
189
+ # Convert collection to list for iteration
190
+ col_list = self.ee_object.toList(count)
191
+
192
+ for i in range(count):
193
+ img = ee.Image(col_list.get(i))
194
+
195
+ # Fetch metadata efficiently in one call
196
+ meta = {}
197
+ try:
198
+ meta = img.toDictionary(["Date_Filter", "system:time_start", "system:index"]).getInfo()
199
+ except Exception:
200
+ pass
201
+
202
+ # --- Resolve Date ---
203
+ # Priority 1: Use the cached client-side list from RadGEEToolbox if available
204
+ if self.radgee_dates and i < len(self.radgee_dates):
205
+ date_val = self.radgee_dates[i]
206
+ # Priority 2: Check for 'Date_Filter' property (RadGEEToolbox standard)
207
+ elif "Date_Filter" in meta:
208
+ date_val = meta["Date_Filter"]
209
+ # Priority 3: Fallback to 'system:time_start'
210
+ elif "system:time_start" in meta:
211
+ date_val = ee.Date(meta["system:time_start"]).format(self.date_pattern).getInfo()
212
+ else:
213
+ date_val = "no_date"
214
+
215
+ # --- Resolve ID ---
216
+ # Use metadata dictionary or fallback to generated index
217
+ sys_index = meta.get("system:index", f"img_{i}")
218
+
219
+ # --- Generate Filename ---
220
+ # Apply pattern. Default is "{date}".
221
+ name_str = self.name_pattern.format(id=sys_index, date=date_val)
222
+
223
+ # Combine with global prefix.
224
+ # If prefix is "MyExport" and date is "2023-01-01", result is "MyExport_2023-01-01"
225
+ final_filename = f"{self.fileNamePrefix}_{name_str}" if self.fileNamePrefix else name_str
226
+
227
+ # Ensure unique description for the task (must be unique per task)
228
+ # We use the date in the description to make it easier to track in the GEE Task Manager
229
+ final_desc = f"{self.description}_{date_val}_{i}"
230
+
231
+ # Construct parameters
232
+ params = {
233
+ "image": img,
234
+ "description": final_desc,
235
+ "folder": self.folder,
236
+ "fileNamePrefix": final_filename,
237
+ "scale": self.scale,
238
+ "region": self.region,
239
+ "crs": self.crs,
240
+ "maxPixels": self.maxPixels,
241
+ "fileFormat": self.fileFormat,
242
+ }
243
+ params.update(self.extra_kwargs)
244
+ params = {k: v for k, v in params.items() if v is not None}
245
+
246
+ task = ee.batch.Export.image.toDrive(**params)
247
+ task.start()
248
+
249
+ print(f"Successfully queued {count} export tasks.")