geebeam 0.1.0__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.
- geebeam/__init__.py +15 -0
- geebeam/climate_indices.py +37 -0
- geebeam/ee_utils.py +40 -0
- geebeam/runner.py +199 -0
- geebeam/sampler.py +38 -0
- geebeam/transforms.py +219 -0
- geebeam-0.1.0.dist-info/METADATA +158 -0
- geebeam-0.1.0.dist-info/RECORD +10 -0
- geebeam-0.1.0.dist-info/WHEEL +4 -0
- geebeam-0.1.0.dist-info/licenses/LICENSE +21 -0
geebeam/__init__.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""Runners
|
|
2
|
+
|
|
3
|
+
Beam and Earth Engine helpers for running data pipelines
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from . import runner, sampler, transforms, ee_utils, climate_indices
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"ee_utils",
|
|
11
|
+
"runner",
|
|
12
|
+
"sampler",
|
|
13
|
+
"transforms",
|
|
14
|
+
"climate_indices",
|
|
15
|
+
]
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Helpers to download non-spatial climate indices"""
|
|
2
|
+
|
|
3
|
+
import pandas as pd
|
|
4
|
+
|
|
5
|
+
def download_clim_indices(
|
|
6
|
+
index_name: str,
|
|
7
|
+
year_start: int,
|
|
8
|
+
year_end: int
|
|
9
|
+
) -> pd.DataFrame:
|
|
10
|
+
clim_registry = {
|
|
11
|
+
'amo':'https://www.ncei.noaa.gov/pub/data/cmb/ersst/v5/index/ersst.v5.amo.dat',
|
|
12
|
+
'soi':'https://psl.noaa.gov/data/timeseries/month/data/soi.long.csv',
|
|
13
|
+
'oni':'https://psl.noaa.gov/data/correlation/oni.csv',
|
|
14
|
+
'mei': 'https://psl.noaa.gov/data/correlation/meiv2.csv',
|
|
15
|
+
'tna': 'https://psl.noaa.gov/data/correlation/tna.csv'
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
try:
|
|
19
|
+
download_url = clim_registry[index_name]
|
|
20
|
+
except KeyError:
|
|
21
|
+
raise ValueError(f'{index_name} not found. Current options are {list(clim_registry.keys())}')
|
|
22
|
+
|
|
23
|
+
if index_name == 'amo':
|
|
24
|
+
df = pd.read_csv(download_url, skiprows=1, sep='\s+')
|
|
25
|
+
df['Date'] = df['Year'].astype(str) + '-' + df['month'].astype(str) + '-01'
|
|
26
|
+
df = df.drop(columns=['Year','month'])[['Date','SSTA']]
|
|
27
|
+
else:
|
|
28
|
+
df = pd.read_csv(download_url)
|
|
29
|
+
|
|
30
|
+
df['Date'] = pd.to_datetime(df['Date'])
|
|
31
|
+
df.columns = ['Date', 'metric']
|
|
32
|
+
|
|
33
|
+
df = df.set_index('Date')
|
|
34
|
+
indexer = (df.index.year >=year_start) & (df.index.year <= year_end)
|
|
35
|
+
return df.loc[indexer]
|
|
36
|
+
|
|
37
|
+
|
geebeam/ee_utils.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Utilities for cleaning, combining, and serializing/deserializing EE objects.
|
|
3
|
+
"""
|
|
4
|
+
import ee
|
|
5
|
+
|
|
6
|
+
def deserialize(obj_json):
|
|
7
|
+
"""Deserialize Earth Engine JSON DAG"""
|
|
8
|
+
return ee.deserializer.fromJSON(obj_json)
|
|
9
|
+
|
|
10
|
+
def serialize(obj_ee):
|
|
11
|
+
"""Serialize Earth Engine object to JSON for Dataflow workers"""
|
|
12
|
+
return ee.serializer.toJSON(obj_ee)
|
|
13
|
+
|
|
14
|
+
def get_band_names(input_list):
|
|
15
|
+
"""Get simplified band_names for output (without prefixed image_id)
|
|
16
|
+
|
|
17
|
+
TODO: Add year to distinguish multiple years?
|
|
18
|
+
"""
|
|
19
|
+
return [
|
|
20
|
+
image.bandNames()
|
|
21
|
+
for image in input_list
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
def build_prepped_image(input_list, split_processing=False):
|
|
25
|
+
"""Combine a list of EE images into single image"""
|
|
26
|
+
band_names = get_band_names(input_list)
|
|
27
|
+
band_names_flat = ee.List(band_names).flatten()
|
|
28
|
+
|
|
29
|
+
if split_processing:
|
|
30
|
+
band_groups = band_names
|
|
31
|
+
else:
|
|
32
|
+
band_groups = [band_names_flat]
|
|
33
|
+
# Final prepped image
|
|
34
|
+
prepped_im = ee.ImageCollection(input_list).toBands().rename(band_names_flat)
|
|
35
|
+
return prepped_im, band_groups
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def list_to_im(input_list):
|
|
39
|
+
prepped_im, _ = build_prepped_image(input_list)
|
|
40
|
+
return prepped_im
|
geebeam/runner.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
"""Prepare and run Beam pipeline to download image 'chips' from Earth Engine
|
|
2
|
+
|
|
3
|
+
Example execution:
|
|
4
|
+
python geebeam_main.py \
|
|
5
|
+
--output_path gs://aic-fire-amazon/results/ \
|
|
6
|
+
--sampling_region ./data/Limites_RAISG_2025/Lim_Raisg.shp \
|
|
7
|
+
--runner DataflowRunner \
|
|
8
|
+
--experiments=use_runner_v2 \
|
|
9
|
+
--max_num_workers=16 \
|
|
10
|
+
--num_workers=8 \
|
|
11
|
+
--requirements_file ./pipeline_requirements.txt
|
|
12
|
+
|
|
13
|
+
"""
|
|
14
|
+
import ee
|
|
15
|
+
import numpy as np
|
|
16
|
+
import apache_beam as beam
|
|
17
|
+
from apache_beam.options.pipeline_options import PipelineOptions
|
|
18
|
+
import tensorflow_data_validation as tfdv
|
|
19
|
+
from tfx_bsl.coders import example_coder
|
|
20
|
+
import argparse
|
|
21
|
+
import os
|
|
22
|
+
from google.protobuf.json_format import MessageToJson
|
|
23
|
+
|
|
24
|
+
from geebeam import ee_utils, sampler, transforms
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def check_if_localrunner(beam_options):
|
|
28
|
+
"""Fixes gRPC timeout issue for local runners."""
|
|
29
|
+
runner = beam_options.get_all_options()['runner']
|
|
30
|
+
if runner is None or runner in ['DirectRunner', 'PrismRunner']:
|
|
31
|
+
return True
|
|
32
|
+
else:
|
|
33
|
+
return False
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def prepare_run_metadata(config):
|
|
37
|
+
ee.Initialize(project=config['project_id'])
|
|
38
|
+
|
|
39
|
+
proj = ee.Projection(config['proj']).atScale(config['scale'])
|
|
40
|
+
proj_dict = proj.getInfo()
|
|
41
|
+
|
|
42
|
+
scale_x = proj_dict['transform'][0]
|
|
43
|
+
scale_y = -proj_dict['transform'][4]
|
|
44
|
+
|
|
45
|
+
return scale_x, scale_y
|
|
46
|
+
|
|
47
|
+
def run(config, image_list, random_seed=None, split_processing=False, extra_metadata={},
|
|
48
|
+
output_path=None, sampling_region=None):
|
|
49
|
+
import logging
|
|
50
|
+
|
|
51
|
+
logging.getLogger().setLevel(logging.INFO)
|
|
52
|
+
|
|
53
|
+
rng = np.random.default_rng(random_seed)
|
|
54
|
+
|
|
55
|
+
parser = argparse.ArgumentParser()
|
|
56
|
+
parser.add_argument(
|
|
57
|
+
"--output_path",
|
|
58
|
+
required=False,
|
|
59
|
+
help="Directory to save TFRecord files (local or GCS).",
|
|
60
|
+
)
|
|
61
|
+
parser.add_argument(
|
|
62
|
+
"--sampling_region",
|
|
63
|
+
required=False,
|
|
64
|
+
help="Local geopandas-readable file of region to sample from randomly."
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
# Beam args are leftover after parsing known args
|
|
68
|
+
args, beam_args = parser.parse_known_args()
|
|
69
|
+
|
|
70
|
+
if args.sampling_region is None:
|
|
71
|
+
args.sampling_region = sampling_region
|
|
72
|
+
if args.output_path is None:
|
|
73
|
+
args.output_path = output_path
|
|
74
|
+
|
|
75
|
+
# Randomly sample points
|
|
76
|
+
roi = sampler.get_roi(args.sampling_region)
|
|
77
|
+
sampled_points = sampler.sample_random_points(roi, config['n_sample'], rng)
|
|
78
|
+
|
|
79
|
+
# Split into training and validation
|
|
80
|
+
input_records = sampler.split_train_validation(
|
|
81
|
+
sampled_points, config['validation_ratio'], rng=rng
|
|
82
|
+
).to_dict('records')
|
|
83
|
+
|
|
84
|
+
# Pre-run info:
|
|
85
|
+
scale_x, scale_y = prepare_run_metadata(config)
|
|
86
|
+
|
|
87
|
+
# Set up pipeline
|
|
88
|
+
beam_options = PipelineOptions(beam_args,
|
|
89
|
+
project=config['project_id'],
|
|
90
|
+
temp_location='gs://aic-fire-amazon/tmp/',
|
|
91
|
+
save_main_session=True,
|
|
92
|
+
use_public_ips=False
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
# Check if a local runner
|
|
96
|
+
is_local = check_if_localrunner(beam_options)
|
|
97
|
+
|
|
98
|
+
# Prepare and serialize inputs
|
|
99
|
+
# band_groups is a list of lists containing bands to export
|
|
100
|
+
# if split_processing = False, will contain one list with all bands
|
|
101
|
+
# if split_processing = True, contains separate band_lists for each image in image_list
|
|
102
|
+
prepped_image, band_groups = ee_utils.build_prepped_image(image_list, split_processing=split_processing)
|
|
103
|
+
serialized_image = ee_utils.serialize(prepped_image)
|
|
104
|
+
|
|
105
|
+
# Execute pipeline
|
|
106
|
+
with beam.Pipeline(options=beam_options) as pipeline:
|
|
107
|
+
|
|
108
|
+
points = pipeline | 'Create points' >> beam.Create(input_records)
|
|
109
|
+
|
|
110
|
+
if is_local:
|
|
111
|
+
batches = (
|
|
112
|
+
points
|
|
113
|
+
| 'Add Dummy Key' >> beam.Map(lambda x: (None, x))
|
|
114
|
+
| 'Reshuffle' >> beam.Reshuffle()
|
|
115
|
+
| 'Force Single Batches' >> beam.GroupIntoBatches(batch_size=1)
|
|
116
|
+
| 'Extract' >> beam.FlatMap(lambda x: x[1])
|
|
117
|
+
)
|
|
118
|
+
else:
|
|
119
|
+
batches = points
|
|
120
|
+
|
|
121
|
+
training_data, validation_data = (
|
|
122
|
+
batches
|
|
123
|
+
| 'Get patch' >> beam.ParDo(transforms.EEComputePatch(
|
|
124
|
+
config,
|
|
125
|
+
serialized_image,
|
|
126
|
+
scale_x,
|
|
127
|
+
scale_y,
|
|
128
|
+
band_groups
|
|
129
|
+
))
|
|
130
|
+
| 'Add metadata' >> beam.ParDo(transforms.AddMetadata(extra_metadata))
|
|
131
|
+
| 'Split dataset' >> beam.Partition(transforms.split_dataset, 2)
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
# Convert to TF examples
|
|
135
|
+
training_examples = (
|
|
136
|
+
training_data
|
|
137
|
+
| 'Train to tf.Example' >> beam.Map(transforms.dict_to_example)
|
|
138
|
+
)
|
|
139
|
+
# Calculate stats on training data
|
|
140
|
+
decoder = example_coder.ExamplesToRecordBatchDecoder()
|
|
141
|
+
stats = (
|
|
142
|
+
training_examples
|
|
143
|
+
| 'Batch' >> beam.BatchElements(
|
|
144
|
+
min_batch_size=10,
|
|
145
|
+
max_batch_size=100)
|
|
146
|
+
| 'Decode to arrow' >> beam.Map(lambda b: decoder.DecodeBatch(b))
|
|
147
|
+
| 'Generate Statistics' >> tfdv.GenerateStatistics()
|
|
148
|
+
)
|
|
149
|
+
stats | 'Write stats' >> tfdv.WriteStatisticsToTFRecord(
|
|
150
|
+
os.path.join(args.output_path, 'stats.tfrecord'))
|
|
151
|
+
|
|
152
|
+
# Write out examples
|
|
153
|
+
(training_examples
|
|
154
|
+
| 'Write training' >> transforms.WriteTFExample(
|
|
155
|
+
os.path.join(args.output_path, 'training'))
|
|
156
|
+
)
|
|
157
|
+
if config['validation_ratio'] > 0:
|
|
158
|
+
validation_examples = (
|
|
159
|
+
validation_data
|
|
160
|
+
| 'Val to tf.Example' >> beam.Map(transforms.dict_to_example)
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
(validation_examples
|
|
164
|
+
| 'Write validation' >> transforms.WriteTFExample(
|
|
165
|
+
os.path.join(args.output_path, 'validation'))
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
# NOTE: testing a few different formats.
|
|
170
|
+
# Need to simplify once we decide on one
|
|
171
|
+
# Infer schema
|
|
172
|
+
stats = tfdv.load_statistics(
|
|
173
|
+
os.path.join(args.output_path, 'stats.tfrecord')
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
schema = tfdv.infer_schema(stats)
|
|
177
|
+
|
|
178
|
+
tfdv.write_schema_text(
|
|
179
|
+
schema,
|
|
180
|
+
os.path.join(args.output_path, 'schema.pbtxt')
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
# Also write as pbtxt, easier to read
|
|
184
|
+
tfdv.write_stats_text(
|
|
185
|
+
stats,
|
|
186
|
+
os.path.join(args.output_path, 'stats.pbtxt')
|
|
187
|
+
)
|
|
188
|
+
|
|
189
|
+
# Also write stats and schema as jsons
|
|
190
|
+
out_schema_json = os.path.join(args.output_path, 'schema.json')
|
|
191
|
+
out_stats_json = os.path.join(args.output_path, 'stats.json')
|
|
192
|
+
if args.output_path.startswith('gs://'):
|
|
193
|
+
transforms.write_json_to_gcs(MessageToJson(schema), out_schema_json)
|
|
194
|
+
transforms.write_json_to_gcs(MessageToJson(stats), out_stats_json)
|
|
195
|
+
else:
|
|
196
|
+
transforms.write_json_to_local(MessageToJson(schema), out_schema_json)
|
|
197
|
+
transforms.write_json_to_local(MessageToJson(stats), out_stats_json)
|
|
198
|
+
|
|
199
|
+
|
geebeam/sampler.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Sample points from region of interest
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
import pandas as pd
|
|
7
|
+
import geopandas as gpd
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def get_roi(sampling_region):
|
|
11
|
+
return gpd.read_file(sampling_region)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def sample_random_points(roi: gpd.GeoDataFrame, n_sample: int, rng: np.random.Generator)->pd.DataFrame:
|
|
15
|
+
"""Get random points within region of interest."""
|
|
16
|
+
sampled_points = roi.sample_points(n_sample, rng=rng).geometry.explode().get_coordinates()
|
|
17
|
+
sampled_points.index = np.arange(sampled_points.shape[0])
|
|
18
|
+
lon = sampled_points.values[:,0]
|
|
19
|
+
lat = sampled_points.values[:,1]
|
|
20
|
+
out_df = pd.DataFrame({
|
|
21
|
+
'lat': lat,
|
|
22
|
+
'lon': lon,
|
|
23
|
+
}
|
|
24
|
+
)
|
|
25
|
+
return out_df
|
|
26
|
+
|
|
27
|
+
def split_train_validation(points_df: pd.DataFrame, validation_ratio: float, rng: np.random.Generator, shuffle: bool = True):
|
|
28
|
+
# Shuffle order
|
|
29
|
+
points_df['split'] = 'train'
|
|
30
|
+
if shuffle:
|
|
31
|
+
points_df = points_df.sample(frac=1, random_state=rng).reset_index(drop=True)
|
|
32
|
+
points_df['id'] = points_df.index
|
|
33
|
+
|
|
34
|
+
# Split
|
|
35
|
+
num_train = round(points_df.shape[0]*(1-validation_ratio))
|
|
36
|
+
points_df.loc[num_train:, 'split'] = 'val'
|
|
37
|
+
|
|
38
|
+
return points_df
|
geebeam/transforms.py
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
"""Beam transforms and related utilities"""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
import io
|
|
5
|
+
import time
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
import tensorflow as tf
|
|
9
|
+
import ee
|
|
10
|
+
import apache_beam as beam
|
|
11
|
+
from apache_beam.io.gcp.gcsio import GcsIO
|
|
12
|
+
|
|
13
|
+
def _bytes_feature(value):
|
|
14
|
+
"""Returns a bytes_list from a string / byte."""
|
|
15
|
+
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
|
|
16
|
+
|
|
17
|
+
def _float_feature(value):
|
|
18
|
+
"""Returns a float_list from a float / double."""
|
|
19
|
+
return tf.train.Feature(float_list=tf.train.FloatList(value=[value]))
|
|
20
|
+
|
|
21
|
+
def _int64_feature(value):
|
|
22
|
+
"""Returns an int64_list from a bool / enum / int / uint."""
|
|
23
|
+
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
|
|
24
|
+
|
|
25
|
+
def write_json_to_local(json_string, local_path):
|
|
26
|
+
data = json_string.encode('utf-8')
|
|
27
|
+
with open(local_path, mode="wb") as f:
|
|
28
|
+
f.write(data)
|
|
29
|
+
|
|
30
|
+
def write_json_to_gcs(json_string, gcs_path):
|
|
31
|
+
data = json_string.encode('utf-8')
|
|
32
|
+
with GcsIO().open(gcs_path, mode="wb") as f:
|
|
33
|
+
f.write(data)
|
|
34
|
+
|
|
35
|
+
def convert_to_iterable(val):
|
|
36
|
+
# Convert to iterable
|
|
37
|
+
try:
|
|
38
|
+
_iter_check = iter(val)
|
|
39
|
+
except TypeError:
|
|
40
|
+
return [val]
|
|
41
|
+
else:
|
|
42
|
+
return val
|
|
43
|
+
|
|
44
|
+
def dict_to_example(element):
|
|
45
|
+
""""Convert structured numpy array to tf.Example proto."""
|
|
46
|
+
# First add metadata
|
|
47
|
+
md_dict = {
|
|
48
|
+
'md_id': _int64_feature(element['metadata']['id']),
|
|
49
|
+
'md_lat': _float_feature(element['metadata']['lat']),
|
|
50
|
+
'md_lon': _float_feature(element['metadata']['lon']),
|
|
51
|
+
}
|
|
52
|
+
for md_key in element['metadata'].keys():
|
|
53
|
+
if md_key not in ['id','lat','lon', 'split']:
|
|
54
|
+
md_dict['md_' + md_key] = tf.train.Feature(float_list=
|
|
55
|
+
tf.train.FloatList(
|
|
56
|
+
value = convert_to_iterable(element['metadata'][md_key])
|
|
57
|
+
)
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
# Build image feature with named bands
|
|
61
|
+
array_dict = {}
|
|
62
|
+
for im_feat in element['array'].keys():#.dtype.names:
|
|
63
|
+
array_dict['im_'+im_feat] = tf.train.Feature(
|
|
64
|
+
float_list = tf.train.FloatList(
|
|
65
|
+
value = element['array'][im_feat].flatten()))
|
|
66
|
+
|
|
67
|
+
# Combine
|
|
68
|
+
feature = {**md_dict, **array_dict}
|
|
69
|
+
|
|
70
|
+
# Build example and serialize
|
|
71
|
+
return tf.train.Example(
|
|
72
|
+
features = tf.train.Features(feature = feature)).SerializeToString()
|
|
73
|
+
|
|
74
|
+
def array_to_example(structured_array):
|
|
75
|
+
""""Convert structured numpy array to tf.Example proto."""
|
|
76
|
+
feature = {}
|
|
77
|
+
for f in structured_array.dtype.names:
|
|
78
|
+
feature[f] = tf.train.Feature(
|
|
79
|
+
float_list = tf.train.FloatList(
|
|
80
|
+
value = structured_array[f].flatten()))
|
|
81
|
+
return tf.train.Example(
|
|
82
|
+
features = tf.train.Features(feature = feature))
|
|
83
|
+
|
|
84
|
+
def split_dataset(element, n_partitions) -> int:
|
|
85
|
+
split_mappings = {
|
|
86
|
+
'train': 0,
|
|
87
|
+
'val': 1,
|
|
88
|
+
'test': 2
|
|
89
|
+
}
|
|
90
|
+
return split_mappings[element['metadata']['split']]
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class EEComputePatch(beam.DoFn):
|
|
94
|
+
"""DoFn() for computing EE patch
|
|
95
|
+
|
|
96
|
+
config (dict): Dictionary containing configuration settings
|
|
97
|
+
in the following key:value pairs:
|
|
98
|
+
project_id (str): Google Cloud project id
|
|
99
|
+
patch_size (int): Patch size, in pixels, of output chips
|
|
100
|
+
scale (float): Final scale, in m
|
|
101
|
+
target_year (int): Year of prediction
|
|
102
|
+
target_key (str): Name of target data, corresponds to key in self.prep_dict
|
|
103
|
+
inputs_keys (list): Names of input data, correspond to keys in self.prep_dict
|
|
104
|
+
proj (str): Projection, e.g. "EPSG:4326"
|
|
105
|
+
"""
|
|
106
|
+
def __init__(self, config, serialized_image, scale_x, scale_y, band_groups):
|
|
107
|
+
self.config = config
|
|
108
|
+
self.serialized_image = serialized_image
|
|
109
|
+
self.scale_x = scale_x
|
|
110
|
+
self.scale_y = scale_y
|
|
111
|
+
self.band_groups = band_groups
|
|
112
|
+
|
|
113
|
+
def setup(self):
|
|
114
|
+
print(f"Initializing Earth Engine for project: {self.config['project_id']}")
|
|
115
|
+
logging.warning("EE setup: starting")
|
|
116
|
+
ee.Initialize(project=self.config['project_id'],
|
|
117
|
+
opt_url='https://earthengine-highvolume.googleapis.com')
|
|
118
|
+
logging.warning("EE setup: finished")
|
|
119
|
+
|
|
120
|
+
def deserialize(self, obj_json):
|
|
121
|
+
return ee.deserializer.fromJSON(obj_json)
|
|
122
|
+
|
|
123
|
+
def _get_pixels(self, im, point):
|
|
124
|
+
# Make a request object.
|
|
125
|
+
request = {
|
|
126
|
+
'expression': im,
|
|
127
|
+
'fileFormat': 'NPY',
|
|
128
|
+
'grid': {
|
|
129
|
+
'dimensions': {
|
|
130
|
+
'width': self.config['patch_size'],
|
|
131
|
+
'height':self.config['patch_size']
|
|
132
|
+
},
|
|
133
|
+
'affineTransform': {
|
|
134
|
+
'scaleX': self.scale_x,
|
|
135
|
+
'shearX': 0,
|
|
136
|
+
'translateX': point['lon'],
|
|
137
|
+
'shearY': 0,
|
|
138
|
+
'scaleY': self.scale_y,
|
|
139
|
+
'translateY': point['lat']
|
|
140
|
+
},
|
|
141
|
+
'crsCode': 'EPSG:4326',
|
|
142
|
+
},
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
raw = ee.data.computePixels(request)
|
|
146
|
+
|
|
147
|
+
if not raw:
|
|
148
|
+
raise RuntimeError("Empty EE response")
|
|
149
|
+
|
|
150
|
+
try:
|
|
151
|
+
arr = np.load(io.BytesIO(raw), allow_pickle=True)
|
|
152
|
+
except Exception as e:
|
|
153
|
+
raise RuntimeError(f"Failed to load NPY for coords {point['id']}") from e
|
|
154
|
+
|
|
155
|
+
return arr
|
|
156
|
+
|
|
157
|
+
def _join_structured_arrays(self, array_list):
|
|
158
|
+
"""Join structured array along features axis"""
|
|
159
|
+
template = array_list[0]
|
|
160
|
+
new_dtype = sum([a.dtype.descr for a in array_list], [])
|
|
161
|
+
merged = np.empty(template.shape, dtype=new_dtype)
|
|
162
|
+
for a in array_list:
|
|
163
|
+
for feat in a.dtype.names:
|
|
164
|
+
merged[feat] = a[feat]
|
|
165
|
+
return merged
|
|
166
|
+
|
|
167
|
+
def _join_struct_arrays_to_dict(self, array_list):
|
|
168
|
+
"""Join structured array along features axis, return as dict"""
|
|
169
|
+
merged_dict = {}
|
|
170
|
+
for a in array_list:
|
|
171
|
+
for feat in a.dtype.names:
|
|
172
|
+
merged_dict[feat] = a[feat]
|
|
173
|
+
return merged_dict
|
|
174
|
+
|
|
175
|
+
def process(self, point):
|
|
176
|
+
"""Compute a patch of pixel, with upper-left corner defined by the coords."""
|
|
177
|
+
logging.warning(f"EE start {point['id']}")
|
|
178
|
+
t0 = time.time()
|
|
179
|
+
out_ars = []
|
|
180
|
+
for band_list in self.band_groups:
|
|
181
|
+
prepped_image = self.deserialize(self.serialized_image).select(band_list)
|
|
182
|
+
out_ars.append(self._get_pixels(prepped_image, point))
|
|
183
|
+
|
|
184
|
+
out_dict = {'metadata': dict(point)}
|
|
185
|
+
out_dict['array'] = self._join_struct_arrays_to_dict(out_ars)
|
|
186
|
+
logging.warning(
|
|
187
|
+
f"EE end {point['id']}, took {time.time() - t0:.1f}s"
|
|
188
|
+
)
|
|
189
|
+
yield out_dict
|
|
190
|
+
|
|
191
|
+
class AddMetadata(beam.DoFn):
|
|
192
|
+
def __init__(self, metadata):
|
|
193
|
+
self.metadata = metadata
|
|
194
|
+
|
|
195
|
+
def process(self, example):
|
|
196
|
+
merged_metadata = {
|
|
197
|
+
**example.get("metadata", {}),
|
|
198
|
+
**self.metadata
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
yield {
|
|
202
|
+
"array": example["array"],
|
|
203
|
+
"metadata": merged_metadata
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
class WriteTFExample(beam.PTransform):
|
|
207
|
+
"""Write example"""
|
|
208
|
+
def __init__(self, output_dir, file_name_suffix='.tfrecord.gz'):
|
|
209
|
+
self.output_dir = output_dir
|
|
210
|
+
self.file_name_suffix = file_name_suffix
|
|
211
|
+
|
|
212
|
+
def expand(self, pcoll):
|
|
213
|
+
return (
|
|
214
|
+
pcoll
|
|
215
|
+
| 'Write to TFRecord' >> beam.io.WriteToTFRecord(
|
|
216
|
+
self.output_dir,
|
|
217
|
+
file_name_suffix=self.file_name_suffix
|
|
218
|
+
)
|
|
219
|
+
)
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: geebeam
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Earth Engine + Apache Beam
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Requires-Python: >=3.10
|
|
8
|
+
Requires-Dist: apache-beam[gcp]>=2.71.0
|
|
9
|
+
Requires-Dist: dill>=0.4.1
|
|
10
|
+
Requires-Dist: earthengine-api>=1.7.10
|
|
11
|
+
Requires-Dist: geopandas>=1.0.1
|
|
12
|
+
Requires-Dist: grpcio>=1.62.3
|
|
13
|
+
Requires-Dist: tensorflow-data-validation>=1.16
|
|
14
|
+
Requires-Dist: tensorflow-metadata>=1.16
|
|
15
|
+
Requires-Dist: tensorflow>=2.16
|
|
16
|
+
Requires-Dist: tfx-bsl>=1.16
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
|
|
19
|
+
# GeeBeam
|
|
20
|
+
|
|
21
|
+
[](https://github.com/kysolvik/geebeam/actions/workflows/pytest-lint.yml)
|
|
22
|
+
|
|
23
|
+
Google Earth Engine + Apache Beam for building geospatial training datasets
|
|
24
|
+
|
|
25
|
+
## Purpose:
|
|
26
|
+
|
|
27
|
+
GeeBeam is a lightweight library for building and executing Apache Beam pipelines that download data "chips" from Google Earth Engine and write them to TensorFlow records for model training.
|
|
28
|
+
|
|
29
|
+
The user defines the Earth Engine images they want to download chips from using the Python earthengine-api. geebeam then serialized the graph-definition of the images so they can be passed to the Beam workers.
|
|
30
|
+
|
|
31
|
+
The pipelines can be run locally or on Google Cloud Dataflow. (Note: currently local jobs are limited to short-running tasks due to grpc "Deadline Exceeded" error).
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
## Install:
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
pip install geebeam
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## Examples:
|
|
41
|
+
|
|
42
|
+
Here we'll create a burned area mask for 2024 using the MCD64A1 product.
|
|
43
|
+
For example, this could be the target variable for a burn risk model.
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
import ee
|
|
47
|
+
import geebeam
|
|
48
|
+
import google
|
|
49
|
+
|
|
50
|
+
# Get default project id from environment (or specify PROJECT_ID manually)
|
|
51
|
+
PROJECT_ID = google.auth.default()[1]
|
|
52
|
+
|
|
53
|
+
# Initialize ee client, replace with your GCP project ID
|
|
54
|
+
ee.Initalize(project=PROJECT_ID)
|
|
55
|
+
|
|
56
|
+
# Build image for download
|
|
57
|
+
burned_2024 = (ee.ImageCollection('MODIS/061/MCD64A1')
|
|
58
|
+
.select('BurnDate')
|
|
59
|
+
.filter(ee.Filter.calendarRange(2024, 2024, 'year'))
|
|
60
|
+
.min()
|
|
61
|
+
.gt(0)
|
|
62
|
+
.rename(['Burn'])
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
# Building and triggering the pipeline is done with a single command:
|
|
66
|
+
geebeam.run(
|
|
67
|
+
image_list = [burned_2024],
|
|
68
|
+
project=PROJECT_ID,
|
|
69
|
+
patch_size=128, # Pixel dimensions in each direction
|
|
70
|
+
scale=500, # Final export resolution in meters
|
|
71
|
+
n_sample=10, # Number of tiles to sample
|
|
72
|
+
validation_ratio=0.2, # Fraction to select as validation data
|
|
73
|
+
output_path='./test/',
|
|
74
|
+
sampling_region=ee.Geometry.Rectangle(-63.0, -9.0, -56.0, -4.0),
|
|
75
|
+
num_workers=2
|
|
76
|
+
)
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Now let's add another dataset: MapBiomas Amazonia forest fraction
|
|
80
|
+
```python
|
|
81
|
+
# MB Land-use/land-cover forest fraction
|
|
82
|
+
# Note that LULC codes less than 10 area forest in MapBiomas Amazon Collection 6
|
|
83
|
+
mb_amz_lulc = (
|
|
84
|
+
ee.Image('projects/mapbiomas-public/assets/amazon/lulc/collection6/mapbiomas_collection60_integration_v1')
|
|
85
|
+
.lt(10)
|
|
86
|
+
.reduceResolution('mean', maxPixels=500)
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
# Exporting both together is as simple as this:
|
|
90
|
+
geebeam.run(
|
|
91
|
+
image_list = [burned_2024, mb_amz_lulc],
|
|
92
|
+
project=PROJECT_ID,
|
|
93
|
+
patch_size=128,
|
|
94
|
+
scale=500,
|
|
95
|
+
n_sample=10,
|
|
96
|
+
validation_ratio=0.2,
|
|
97
|
+
output_path='./test/',
|
|
98
|
+
sampling_region=ee.Geometry.Rectangle(-63.0, -9.0, -56.0, -4.0),
|
|
99
|
+
num_workers=2
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
### Dataflow:
|
|
105
|
+
|
|
106
|
+
The export process can be scaled to many workers via Google Cloud DataFlow:
|
|
107
|
+
|
|
108
|
+
```bash
|
|
109
|
+
python examples/geebeam_run.py \
|
|
110
|
+
--region us-east1 \
|
|
111
|
+
--worker_zone us-east1-b \
|
|
112
|
+
--runner DataflowRunner \
|
|
113
|
+
--max_num_workers=8 \
|
|
114
|
+
--num_workers=1 \
|
|
115
|
+
--experiments=use_runner_v2 \
|
|
116
|
+
--machine_type=n2-highmem-2
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
Note that in this case the output_path defined in geebeam_run.py should be a Google Cloud Storage path.
|
|
120
|
+
|
|
121
|
+
#### Artifact registry setup:
|
|
122
|
+
|
|
123
|
+
To speed up the start-up and running of jobs on DataFlow, you can build a Docker image containing `geebeam` and it's dependencies.
|
|
124
|
+
|
|
125
|
+
See instructions on Google Cloud
|
|
126
|
+
|
|
127
|
+
First, you'll need to have Docker installed on your computer, either just [Docker Engine](https://docs.docker.com/engine/) or full [Docker Desktop](https://docs.docker.com/desktop/) will do.
|
|
128
|
+
|
|
129
|
+
Next, you'll need to create a Google Artifact Registry respository and configure your Docker to authenticate requests for the Artifact Registry. [Google Cloud DataFlow documentation has step-by-step instructions](https://docs.cloud.google.com/dataflow/docs/guides/build-container-image#before_you_begin).
|
|
130
|
+
|
|
131
|
+
Now you can pre-build the container at the start of your DataFlow job:
|
|
132
|
+
|
|
133
|
+
```bash
|
|
134
|
+
python examples/geebeam_run.py \
|
|
135
|
+
--region us-east1 \
|
|
136
|
+
--worker_zone us-east1-b \
|
|
137
|
+
--runner DataflowRunner \
|
|
138
|
+
--max_num_workers=8 \
|
|
139
|
+
--num_workers=1 \
|
|
140
|
+
--experiments=use_runner_v2 \
|
|
141
|
+
--machine_type=n2-highmem-2
|
|
142
|
+
--prebuild_sdk_container_engine=local_docker \
|
|
143
|
+
--docker_registry_push_url=us-east1-docker.pkg.dev/[PROJECT_ID]/[REPO_NAME]/[IMAGE_NAME] \
|
|
144
|
+
--setup_file=./setup.py
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
Next time you can use the existing image with:
|
|
148
|
+
|
|
149
|
+
```bash
|
|
150
|
+
--sdk_container_image=us-east1-docker.pkg.dev/[PROJECT_ID]/[REPO_NAME]/[IMAGE_NAME]:[IMAGE_TAG]
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
## Alternatives:
|
|
155
|
+
|
|
156
|
+
- [GeeFlow](https://github.com/google-deepmind/geeflow): Google DeepMind's GeeFlow fulfills a similar purpose. It is more flexible, allowing for more user control of data processing, reprojection, and writing, but slower and no longer actively maintained. With the goal of meeting *most* users' needs, GeeBeam is designed to be easier and quicker to use, but allows from more limited data transformations.
|
|
157
|
+
- Export training data to Google Cloud Storage then download chips from there: This works, but if you need to get data from many different datasets it's slow to export all that data to Cloud Storage and can be expensive to store it there if you don't delete it quickly. This also uses a lot of Earth Engine compute hours, which are now subject to stricter monthly limits.
|
|
158
|
+
- [Xee](https://github.com/google/Xee): Xee allows for accessing Earth Engine objects as xarray.Datasets. You could use this to define a xarray.Dataset and download "chips" from it, but geebeam interfaces with Beam to automatically parallelize this task.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
geebeam/__init__.py,sha256=Ece26o9RG19z6fmo5IWPiN2vs5JplaWs0J_8t82n-0Y,245
|
|
2
|
+
geebeam/climate_indices.py,sha256=LwpJH3lcPvldXWpgHPgPxiGtQO1mUtfc9FYWeN8VQag,1268
|
|
3
|
+
geebeam/ee_utils.py,sha256=pf_uOHu4KT3B_ktmddC4O2xz2nGelIS8DRybqBf4qVE,1157
|
|
4
|
+
geebeam/runner.py,sha256=PdYenZq3cs3NrBrbPy4GRX8s8le4e2F9byquqOyd78Y,6808
|
|
5
|
+
geebeam/sampler.py,sha256=xaL7s4DDUTPXVdMLQ6iEp8ahxldYYtlyk4UfYGIwaPc,1116
|
|
6
|
+
geebeam/transforms.py,sha256=rb8muwQZf5PsbgnMkC6--9HKZ82fOmroKbxKyDEv9Nc,7367
|
|
7
|
+
geebeam-0.1.0.dist-info/METADATA,sha256=O9oK8mre1q0wZuJwLx0-TJ4o8cQaPfwPExN5mcb0AWA,6121
|
|
8
|
+
geebeam-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
|
|
9
|
+
geebeam-0.1.0.dist-info/licenses/LICENSE,sha256=F44TOHyTdGJUgFJsTYjcLgROiD03R3B8TyTmS1wZCyA,1069
|
|
10
|
+
geebeam-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Kylen Solvik
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|