|
1 | 1 | from datetime import datetime, timedelta |
2 | 2 | from pathlib import Path |
3 | 3 |
|
4 | | -import asf_search as search |
| 4 | +import asf_search as asf |
| 5 | +import hyp3_sdk |
5 | 6 | import numpy as np |
6 | 7 | import rioxarray |
7 | 8 | import shapely |
8 | 9 | import xarray as xr |
9 | | -from asf_search import ASFSearchResults, S1Product, constants |
10 | | -from hyp3_sdk import Batch, HyP3, Job |
11 | | -from hyp3_sdk.util import extract_zipped_product |
12 | 10 |
|
| 11 | +from satchip import utils |
13 | 12 | from satchip.chip_xr_base import create_template_da |
14 | 13 | from satchip.terra_mind_grid import TerraMindChip |
15 | 14 |
|
16 | 15 |
|
17 | | -def get_pct_intersect(product: S1Product, roi: shapely.geometry.Polygon) -> int: |
| 16 | +def get_rtc_paths_for_chips( |
| 17 | + terra_mind_chips: list[TerraMindChip], bounds: list[float], scratch_dir: Path, opts: utils.ChipDataOpts |
| 18 | +) -> dict[str, list[Path]]: |
| 19 | + _check_bounds_size(bounds) |
| 20 | + granules = _get_granules(bounds, opts['date_start'], opts['date_end']) |
| 21 | + slcs_for_chips = _get_slcs_for_each_chip(terra_mind_chips, granules, opts['strategy']) |
| 22 | + assert len(slcs_for_chips) == len(terra_mind_chips) |
| 23 | + |
| 24 | + rtc_paths_for_chips = _get_rtcs_for(slcs_for_chips, scratch_dir) |
| 25 | + return rtc_paths_for_chips |
| 26 | + |
| 27 | + |
| 28 | +def _check_bounds_size(bounds: list[float]) -> None: |
| 29 | + min_lon, min_lat, max_lon, max_lat = bounds |
| 30 | + MAX_BOUND_AREA_DEGREES = 3 |
| 31 | + bounds_area_degrees = (max_lon - min_lon) * (max_lat - min_lat) |
| 32 | + |
| 33 | + err_message = f'Bounds area is to large ({bounds_area_degrees}). Must be less than {MAX_BOUND_AREA_DEGREES} degrees' |
| 34 | + assert bounds_area_degrees < MAX_BOUND_AREA_DEGREES, err_message |
| 35 | + |
| 36 | + |
| 37 | +def _get_granules(bounds: list[float], date_start: datetime, date_end: datetime) -> list[asf.S1Product]: |
| 38 | + date_start = date_start |
| 39 | + date_end = date_end + timedelta(days=1) # inclusive end |
| 40 | + roi = shapely.box(*bounds) |
| 41 | + search_results = asf.geo_search( |
| 42 | + intersectsWith=roi.wkt, |
| 43 | + start=date_start, |
| 44 | + end=date_end, |
| 45 | + beamMode=asf.constants.BEAMMODE.IW, |
| 46 | + polarization=asf.constants.POLARIZATION.VV_VH, |
| 47 | + platform=asf.constants.PLATFORM.SENTINEL1, |
| 48 | + processingLevel=asf.constants.PRODUCT_TYPE.SLC, |
| 49 | + ) |
| 50 | + |
| 51 | + return list(search_results) |
| 52 | + |
| 53 | + |
| 54 | +def _get_slcs_for_each_chip( |
| 55 | + chips: list[TerraMindChip], granules: list[asf.S1Product], strategy: str, intersection_pct: int = 95 |
| 56 | +) -> dict[str, list[asf.S1Product]]: |
| 57 | + slcs_for_chips: dict[str, list[asf.S1Product]] = {} |
| 58 | + |
| 59 | + for chip in chips: |
| 60 | + chip_roi = shapely.box(*chip.bounds) |
| 61 | + intersecting = [granule for granule in granules if _get_pct_intersect(granule, chip_roi) > intersection_pct] |
| 62 | + intersecting = sorted(intersecting, key=lambda g: (-_get_pct_intersect(g, chip_roi), g.properties['startTime'])) |
| 63 | + |
| 64 | + if len(intersecting) < 1: |
| 65 | + raise ValueError(f'No products found for chip {chip.name} in given date range') |
| 66 | + |
| 67 | + if strategy == 'BEST': |
| 68 | + slcs_for_chips[chip.name] = intersecting[:1] |
| 69 | + else: |
| 70 | + slcs_for_chips[chip.name] = intersecting |
| 71 | + |
| 72 | + return slcs_for_chips |
| 73 | + |
| 74 | + |
| 75 | +def _get_pct_intersect(product: asf.S1Product, roi: shapely.geometry.Polygon) -> int: |
18 | 76 | footprint = shapely.geometry.shape(product.geometry) |
19 | 77 | intersection = int(np.round(100 * roi.intersection(footprint).area / roi.area)) |
20 | 78 | return intersection |
21 | 79 |
|
22 | 80 |
|
23 | | -def download_hyp3_rtc(job: Job, scratch_dir: Path) -> tuple[Path, Path]: |
| 81 | +def _get_rtcs_for(slcs_for_chips: dict[str, list[asf.S1Product]], scratch_dir: Path) -> dict[str, list[Path]]: |
| 82 | + flat_slcs = sum(slcs_for_chips.values(), []) |
| 83 | + slc_names = set(granule.properties['sceneName'] for granule in flat_slcs) |
| 84 | + |
| 85 | + finished_rtc_jobs = _process_rtcs(slc_names) |
| 86 | + |
| 87 | + paths_for_slc_name: dict[str, Path] = {} |
| 88 | + for job in finished_rtc_jobs: |
| 89 | + rtc_path = _download_hyp3_rtc(job, scratch_dir) |
| 90 | + slc_name = job.job_parameters['granules'][0] |
| 91 | + |
| 92 | + paths_for_slc_name[slc_name] = rtc_path |
| 93 | + |
| 94 | + rtc_paths_for_chips: dict[str, list[Path]] = {} |
| 95 | + for chip_name, chip_slcs in slcs_for_chips.items(): |
| 96 | + rtc_paths = [paths_for_slc_name[name.properties['sceneName']] for name in chip_slcs] |
| 97 | + rtc_paths_for_chips[chip_name] = rtc_paths |
| 98 | + |
| 99 | + return rtc_paths_for_chips |
| 100 | + |
| 101 | + |
| 102 | +def _process_rtcs(slc_names: set[str]) -> hyp3_sdk.Batch: |
| 103 | + hyp3 = hyp3_sdk.HyP3() |
| 104 | + jobs_by_scene_name = _get_rtc_jobs_by_scene_name(hyp3) |
| 105 | + |
| 106 | + hyp3_jobs = [] |
| 107 | + for slc_name in slc_names: |
| 108 | + if slc_name in jobs_by_scene_name: |
| 109 | + job = jobs_by_scene_name[slc_name] |
| 110 | + hyp3_jobs.append(job) |
| 111 | + else: |
| 112 | + new_batch = hyp3.submit_rtc_job(slc_name, radiometry='gamma0', resolution=20) |
| 113 | + hyp3_jobs.append(list(new_batch)[0]) |
| 114 | + |
| 115 | + batch = hyp3_sdk.Batch(hyp3_jobs) |
| 116 | + batch = hyp3.watch(batch) |
| 117 | + assert all([j.succeeded() for j in batch]), 'One or more HyP3 jobs failed' |
| 118 | + |
| 119 | + return batch |
| 120 | + |
| 121 | + |
| 122 | +def _get_rtc_jobs_by_scene_name(hyp3: hyp3_sdk.HyP3) -> dict[str, hyp3_sdk.Job]: |
| 123 | + jobs_by_scene_name = {} |
| 124 | + |
| 125 | + for job in hyp3.find_jobs(job_type='RTC_GAMMA'): |
| 126 | + if not _is_valid_rtc_job(job): |
| 127 | + continue |
| 128 | + |
| 129 | + name = job.job_parameters['granules'][0] |
| 130 | + jobs_by_scene_name[name] = job |
| 131 | + |
| 132 | + return jobs_by_scene_name |
| 133 | + |
| 134 | + |
| 135 | +def _is_valid_rtc_job(job: hyp3_sdk.Job) -> bool: |
| 136 | + return ( |
| 137 | + not job.failed() |
| 138 | + and not job.expired() |
| 139 | + and job.job_parameters['radiometry'] == 'gamma0' |
| 140 | + and job.job_parameters['resolution'] == 20 |
| 141 | + ) |
| 142 | + |
| 143 | + |
| 144 | +def _download_hyp3_rtc(job: hyp3_sdk.Job, scratch_dir: Path) -> tuple[Path, Path]: |
24 | 145 | output_path = scratch_dir / job.to_dict()['files'][0]['filename'] |
25 | 146 | output_dir = output_path.with_suffix('') |
26 | 147 | output_zip = output_path.with_suffix('.zip') |
27 | 148 | if not output_dir.exists(): |
28 | 149 | job.download_files(location=scratch_dir) |
29 | | - extract_zipped_product(output_zip) |
| 150 | + hyp3_sdk.util.extract_zipped_product(output_zip) |
30 | 151 | vv_path = list(output_dir.glob('*_VV.tif'))[0] |
31 | 152 | vh_path = list(output_dir.glob('*_VH.tif'))[0] |
32 | 153 | return vv_path, vh_path |
33 | 154 |
|
34 | 155 |
|
35 | | -def get_hyp3_rtcs(items: ASFSearchResults, roi: shapely.geometry.Polygon, strategy: str, scratch_dir: Path) -> list: |
36 | | - valid_items = [item for item in items if get_pct_intersect(item, roi) > 95] |
37 | | - valid_items = sorted(items, key=lambda x: (-get_pct_intersect(x, roi), x.properties['startTime'])) |
38 | | - if strategy == 'BEST': |
39 | | - valid_items = valid_items[:1] |
40 | | - hyp3 = HyP3() |
41 | | - old_jobs = [j for j in hyp3.find_jobs(job_type='RTC_GAMMA') if not j.failed() and not j.expired()] |
42 | | - old_jobs = [j for j in old_jobs if j.job_parameters['radiometry'] == 'gamma0'] # type: ignore |
43 | | - old_jobs = [j for j in old_jobs if j.job_parameters['resolution'] == 20] # type: ignore |
44 | | - jobs = [] |
45 | | - for item in valid_items: |
46 | | - scene_name = item.properties['sceneName'] |
47 | | - matching_jobs = [j for j in old_jobs if j.job_parameters['granules'] == [scene_name]] # type: ignore |
48 | | - if len(matching_jobs) == 0: |
49 | | - new_batch = hyp3.submit_rtc_job(scene_name, radiometry='gamma0', resolution=20) |
50 | | - jobs.append(list(new_batch)[0]) |
51 | | - else: |
52 | | - jobs.append(matching_jobs[0]) |
53 | | - jobs = Batch(jobs) |
54 | | - hyp3.watch(jobs) |
55 | | - assert all([j.succeeded() for j in jobs]), 'One or more HyP3 jobs failed' |
56 | | - paths = [download_hyp3_rtc(job, scratch_dir) for job in jobs] |
57 | | - return paths |
58 | | - |
59 | | - |
60 | | -def get_s1rtc_data(chip: TerraMindChip, scratch_dir: Path, opts: dict) -> xr.DataArray: |
61 | | - date_start = opts['date_start'] |
62 | | - date_end = opts['date_end'] + timedelta(days=1) # inclusive end |
| 156 | +def get_s1rtc_chip_data( |
| 157 | + chip: TerraMindChip, image_sets: list[Path], scratch_dir: Path, opts: utils.ChipDataOpts |
| 158 | +) -> xr.DataArray: |
63 | 159 | roi = shapely.box(*chip.bounds) |
64 | | - search_results = search.geo_search( |
65 | | - intersectsWith=roi.wkt, |
66 | | - start=date_start, |
67 | | - end=date_end, |
68 | | - beamMode=constants.BEAMMODE.IW, |
69 | | - polarization=constants.POLARIZATION.VV_VH, |
70 | | - platform=constants.PLATFORM.SENTINEL1, |
71 | | - processingLevel=constants.PRODUCT_TYPE.SLC, |
72 | | - ) |
73 | | - if len(search_results) == 0: |
74 | | - raise ValueError(f'No products found for chip {chip.name} in date range {date_start} to {date_end}') |
75 | | - strategy = opts.get('strategy', 'BEST').upper() |
76 | | - image_sets = get_hyp3_rtcs(search_results, roi, strategy, scratch_dir) |
77 | 160 | das = [] |
78 | 161 | template = create_template_da(chip) |
79 | 162 | for image_set in image_sets: |
|
0 commit comments