Apply current workspace changes

This commit is contained in:
2026-04-22 01:52:21 +08:00
parent cf34b9a8ed
commit cb518b431f
449 changed files with 92252 additions and 321 deletions
+403
View File
@@ -0,0 +1,403 @@
from __future__ import annotations
import json
import math
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import Any
import numpy as np
MASTER_DATE = "20230726"
SLAVE_DATES = ("20230624", "20230920")
PATCH_SIZE = 512
GAMMA_FLOAT32 = np.dtype(">f4")
@dataclass
class GammaImageShape:
width: int
lines: int
def parse_gamma_par_value(path: Path, key: str) -> str:
prefix = key.strip() + ":"
for line in path.read_text(encoding="utf-8", errors="ignore").splitlines():
stripped = line.strip()
if stripped.startswith(prefix):
_, _, tail = stripped.partition(":")
return tail.strip().split()[0]
raise ValueError(f"Missing key '{key}' in {path}")
def parse_gamma_shape(path: Path) -> GammaImageShape:
width = int(float(parse_gamma_par_value(path, "range_samples")))
lines = int(float(parse_gamma_par_value(path, "azimuth_lines")))
return GammaImageShape(width=width, lines=lines)
def read_float32_image(path: Path, shape: GammaImageShape) -> np.ndarray:
arr = np.fromfile(path, dtype=GAMMA_FLOAT32)
expected = shape.width * shape.lines
if arr.size != expected:
raise ValueError(f"Unexpected size for {path}: expected {expected}, got {arr.size}")
return arr.reshape(shape.lines, shape.width)
def read_lt0_lookup(path: Path, shape: GammaImageShape) -> np.ndarray:
arr = np.fromfile(path, dtype=GAMMA_FLOAT32)
expected = shape.width * shape.lines * 2
if arr.size != expected:
raise ValueError(f"Unexpected lt0 size for {path}: expected {expected}, got {arr.size}")
return arr.reshape(shape.lines, shape.width, 2)
def center_slice(size: int, patch: int) -> slice:
patch = min(size, patch)
start = max(0, (size - patch) // 2)
stop = start + patch
return slice(start, stop)
def safe_float(value: Any) -> float | None:
if value is None:
return None
try:
result = float(value)
except Exception:
return None
if math.isnan(result) or math.isinf(result):
return None
return result
def summarize_array(arr: np.ndarray, *, patch_size: int = PATCH_SIZE) -> dict[str, Any]:
finite = np.isfinite(arr)
zeros = finite & (arr == 0)
nonzero = finite & (arr != 0)
ys = center_slice(arr.shape[0], patch_size)
xs = center_slice(arr.shape[1], patch_size)
patch = arr[ys, xs]
patch_finite = np.isfinite(patch)
patch_zeros = patch_finite & (patch == 0)
patch_nonzero = patch_finite & (patch != 0)
nz = arr[nonzero]
patch_nz = patch[patch_nonzero]
stats: dict[str, Any] = {
"shape": [int(arr.shape[0]), int(arr.shape[1])],
"count": int(arr.size),
"finite_count": int(finite.sum()),
"zero_count": int(zeros.sum()),
"zero_ratio": safe_float(zeros.sum() / arr.size if arr.size else None),
"nonzero_count": int(nonzero.sum()),
"center_patch_shape": [int(patch.shape[0]), int(patch.shape[1])],
"center_patch_count": int(patch.size),
"center_patch_zero_count": int(patch_zeros.sum()),
"center_patch_zero_ratio": safe_float(patch_zeros.sum() / patch.size if patch.size else None),
"center_patch_nonzero_count": int(patch_nonzero.sum()),
}
if nz.size:
stats.update(
{
"min_nonzero": safe_float(nz.min()),
"max_nonzero": safe_float(nz.max()),
"mean_nonzero": safe_float(nz.mean()),
"std_nonzero": safe_float(nz.std()),
}
)
if patch_nz.size:
stats.update(
{
"center_patch_min_nonzero": safe_float(patch_nz.min()),
"center_patch_max_nonzero": safe_float(patch_nz.max()),
"center_patch_mean_nonzero": safe_float(patch_nz.mean()),
"center_patch_std_nonzero": safe_float(patch_nz.std()),
}
)
return stats
def summarize_lt0(arr: np.ndarray, *, patch_size: int = PATCH_SIZE) -> dict[str, Any]:
rng = arr[:, :, 0]
az = arr[:, :, 1]
finite = np.isfinite(rng) & np.isfinite(az)
zero_pair = finite & (rng == 0) & (az == 0)
valid_pair = finite & (~zero_pair)
magnitude = np.sqrt(np.square(rng, dtype=np.float64) + np.square(az, dtype=np.float64))
ys = center_slice(arr.shape[0], patch_size)
xs = center_slice(arr.shape[1], patch_size)
patch_valid = valid_pair[ys, xs]
patch_zero = zero_pair[ys, xs]
patch_mag = magnitude[ys, xs][patch_valid]
all_mag = magnitude[valid_pair]
stats: dict[str, Any] = {
"shape": [int(arr.shape[0]), int(arr.shape[1]), 2],
"count": int(arr.shape[0] * arr.shape[1]),
"valid_pair_count": int(valid_pair.sum()),
"valid_pair_ratio": safe_float(valid_pair.sum() / valid_pair.size if valid_pair.size else None),
"zero_pair_count": int(zero_pair.sum()),
"zero_pair_ratio": safe_float(zero_pair.sum() / zero_pair.size if zero_pair.size else None),
"center_patch_shape": [int(patch_valid.shape[0]), int(patch_valid.shape[1])],
"center_patch_valid_pair_count": int(patch_valid.sum()),
"center_patch_valid_pair_ratio": safe_float(patch_valid.sum() / patch_valid.size if patch_valid.size else None),
"center_patch_zero_pair_count": int(patch_zero.sum()),
"center_patch_zero_pair_ratio": safe_float(patch_zero.sum() / patch_zero.size if patch_zero.size else None),
}
if all_mag.size:
stats.update(
{
"magnitude_min": safe_float(all_mag.min()),
"magnitude_max": safe_float(all_mag.max()),
"magnitude_mean": safe_float(all_mag.mean()),
"magnitude_std": safe_float(all_mag.std()),
}
)
if patch_mag.size:
stats.update(
{
"center_patch_magnitude_min": safe_float(patch_mag.min()),
"center_patch_magnitude_max": safe_float(patch_mag.max()),
"center_patch_magnitude_mean": safe_float(patch_mag.mean()),
"center_patch_magnitude_std": safe_float(patch_mag.std()),
}
)
return stats
def summarize_overlap(a: np.ndarray, b: np.ndarray, *, patch_size: int = PATCH_SIZE) -> dict[str, Any]:
if a.shape != b.shape:
raise ValueError(f"Shape mismatch for overlap: {a.shape} vs {b.shape}")
finite_a = np.isfinite(a)
finite_b = np.isfinite(b)
nz_a = finite_a & (a != 0)
nz_b = finite_b & (b != 0)
overlap = nz_a & nz_b
ys = center_slice(a.shape[0], patch_size)
xs = center_slice(a.shape[1], patch_size)
patch_overlap = overlap[ys, xs]
patch_nz_a = nz_a[ys, xs]
patch_nz_b = nz_b[ys, xs]
return {
"shape": [int(a.shape[0]), int(a.shape[1])],
"overlap_nonzero_count": int(overlap.sum()),
"overlap_nonzero_ratio": safe_float(overlap.sum() / overlap.size if overlap.size else None),
"a_nonzero_count": int(nz_a.sum()),
"b_nonzero_count": int(nz_b.sum()),
"center_patch_overlap_nonzero_count": int(patch_overlap.sum()),
"center_patch_overlap_nonzero_ratio": safe_float(patch_overlap.sum() / patch_overlap.size if patch_overlap.size else None),
"center_patch_a_nonzero_count": int(patch_nz_a.sum()),
"center_patch_b_nonzero_count": int(patch_nz_b.sum()),
}
def scale_to_u8(arr: np.ndarray) -> np.ndarray:
finite = np.isfinite(arr)
valid = arr[finite & (arr != 0)]
if valid.size == 0:
return np.zeros(arr.shape, dtype=np.uint8)
lo = np.percentile(valid, 1)
hi = np.percentile(valid, 99)
if not np.isfinite(lo) or not np.isfinite(hi) or hi <= lo:
lo = float(valid.min())
hi = float(valid.max()) if valid.size else lo + 1.0
if hi <= lo:
hi = lo + 1.0
scaled = np.clip((arr - lo) / (hi - lo), 0, 1)
scaled[~finite] = 0
scaled[arr == 0] = 0
return np.round(scaled * 255.0).astype(np.uint8)
def write_pgm(path: Path, arr_u8: np.ndarray) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
header = f"P5\n{arr_u8.shape[1]} {arr_u8.shape[0]}\n255\n".encode("ascii")
with path.open("wb") as fp:
fp.write(header)
fp.write(arr_u8.tobytes())
def write_quicklook(path: Path, arr: np.ndarray) -> None:
write_pgm(path, scale_to_u8(arr))
def case_root(run_root: Path, case_name: str) -> Path:
return run_root / case_name / "pyint_stage"
def audit_case(run_root: Path, case_name: str, out_root: Path) -> dict[str, Any]:
case_dir = case_root(run_root, case_name)
dem_dir = case_dir / "DEM"
out_case_root = out_root / case_name
out_case_root.mkdir(parents=True, exist_ok=True)
master_shape = parse_gamma_shape(dem_dir / f"{MASTER_DATE}_2rlks.amp.par")
hgtsim = read_float32_image(dem_dir / f"{MASTER_DATE}_2rlks.rdc.dem", master_shape)
lt0_quicklook_written = False
result: dict[str, Any] = {
"case": case_name,
"master_date": MASTER_DATE,
"master_shape": {"width": master_shape.width, "lines": master_shape.lines},
"dem": {
"hgtsim": summarize_array(hgtsim),
},
"slaves": {},
}
write_quicklook(out_case_root / "hgtsim.pgm", hgtsim)
for slave_date in SLAVE_DATES:
slc_dir = case_dir / "SLC" / slave_date
rslc_dir = case_dir / "RSLC" / slave_date
slave_shape = parse_gamma_shape(slc_dir / f"{slave_date}_2rlks.amp.par")
samp = read_float32_image(slc_dir / f"{slave_date}_2rlks.amp", slave_shape)
mli0 = read_float32_image(rslc_dir / "mli0", slave_shape)
lt0 = read_lt0_lookup(rslc_dir / "lt0", master_shape)
lt0_mag = np.sqrt(np.square(lt0[:, :, 0], dtype=np.float64) + np.square(lt0[:, :, 1], dtype=np.float64))
slave_out = out_case_root / slave_date
slave_out.mkdir(parents=True, exist_ok=True)
write_quicklook(slave_out / "samp.pgm", samp)
write_quicklook(slave_out / "mli0.pgm", mli0)
if not lt0_quicklook_written:
write_quicklook(out_case_root / "lt0_magnitude.pgm", lt0_mag.astype(np.float32))
lt0_quicklook_written = True
slave_summary = {
"shape": {"width": slave_shape.width, "lines": slave_shape.lines},
"samp": summarize_array(samp),
"mli0": summarize_array(mli0),
"lt0": summarize_lt0(lt0),
"mli0_samp_overlap": summarize_overlap(mli0, samp),
}
result["slaves"][slave_date] = slave_summary
(slave_out / "summary.json").write_text(
json.dumps(slave_summary, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8",
)
(out_case_root / "summary.json").write_text(
json.dumps(result, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8",
)
return result
def build_summary_rows(result: dict[str, Any]) -> list[dict[str, Any]]:
rows: list[dict[str, Any]] = []
rows.append(
{
"case": result["case"],
"date": result["master_date"],
"artifact": "hgtsim",
"zero_ratio": result["dem"]["hgtsim"].get("zero_ratio"),
"center_patch_zero_ratio": result["dem"]["hgtsim"].get("center_patch_zero_ratio"),
"overlap_ratio": None,
"center_patch_overlap_ratio": None,
}
)
for slave_date, payload in result["slaves"].items():
for artifact in ("samp", "mli0"):
stats = payload[artifact]
rows.append(
{
"case": result["case"],
"date": slave_date,
"artifact": artifact,
"zero_ratio": stats.get("zero_ratio"),
"center_patch_zero_ratio": stats.get("center_patch_zero_ratio"),
"overlap_ratio": None,
"center_patch_overlap_ratio": None,
}
)
lt0 = payload["lt0"]
rows.append(
{
"case": result["case"],
"date": slave_date,
"artifact": "lt0",
"zero_ratio": lt0.get("zero_pair_ratio"),
"center_patch_zero_ratio": lt0.get("center_patch_zero_pair_ratio"),
"overlap_ratio": lt0.get("valid_pair_ratio"),
"center_patch_overlap_ratio": lt0.get("center_patch_valid_pair_ratio"),
}
)
overlap = payload["mli0_samp_overlap"]
rows.append(
{
"case": result["case"],
"date": slave_date,
"artifact": "mli0_samp_overlap",
"zero_ratio": None,
"center_patch_zero_ratio": None,
"overlap_ratio": overlap.get("overlap_nonzero_ratio"),
"center_patch_overlap_ratio": overlap.get("center_patch_overlap_nonzero_ratio"),
}
)
return rows
def write_summary_tsv(path: Path, rows: list[dict[str, Any]]) -> None:
header = [
"case",
"date",
"artifact",
"zero_ratio",
"center_patch_zero_ratio",
"overlap_ratio",
"center_patch_overlap_ratio",
]
lines = ["\t".join(header)]
for row in rows:
values = []
for key in header:
value = row.get(key)
if isinstance(value, float):
values.append(f"{value:.6f}")
elif value is None:
values.append("")
else:
values.append(str(value))
lines.append("\t".join(values))
path.write_text("\n".join(lines) + "\n", encoding="utf-8")
def main() -> int:
if len(sys.argv) < 2:
print("usage: audit_lt1_dem_geometry_chain.py <run_root> [case ...]", file=sys.stderr)
return 2
run_root = Path(sys.argv[1]).resolve()
case_names = tuple(sys.argv[2:]) if len(sys.argv) > 2 else ("case_A_baseline", "case_C_precise_orbit_rewrite")
out_root = run_root / "audit_dem_geometry"
out_root.mkdir(parents=True, exist_ok=True)
all_results = []
all_rows: list[dict[str, Any]] = []
for case_name in case_names:
result = audit_case(run_root, case_name, out_root)
all_results.append(result)
all_rows.extend(build_summary_rows(result))
(out_root / "audit_summary.json").write_text(
json.dumps({"run_root": str(run_root), "results": all_results}, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8",
)
write_summary_tsv(out_root / "audit_summary.tsv", all_rows)
print(json.dumps({"run_root": str(run_root), "output_dir": str(out_root), "case_count": len(case_names)}, ensure_ascii=False))
return 0
if __name__ == "__main__":
raise SystemExit(main())
@@ -0,0 +1,204 @@
from __future__ import annotations
import importlib.util
import json
import sys
from pathlib import Path
from typing import Any
def load_base_module(script_path: Path):
spec = importlib.util.spec_from_file_location("audit_lt1_dem_geometry_chain_base", script_path)
if spec is None or spec.loader is None:
raise RuntimeError(f"Unable to load base audit script: {script_path}")
module = importlib.util.module_from_spec(spec)
sys.modules[spec.name] = module
spec.loader.exec_module(module)
return module
def build_summary_rows(result: dict[str, Any]) -> list[dict[str, Any]]:
rows: list[dict[str, Any]] = []
rows.append(
{
"root": result["root"],
"date": result["master_date"],
"artifact": "hgtsim",
"zero_ratio": result["dem"]["hgtsim"].get("zero_ratio"),
"center_patch_zero_ratio": result["dem"]["hgtsim"].get("center_patch_zero_ratio"),
"overlap_ratio": None,
"center_patch_overlap_ratio": None,
}
)
for slave_date, payload in result["slaves"].items():
for artifact in ("samp", "mli0"):
stats = payload[artifact]
rows.append(
{
"root": result["root"],
"date": slave_date,
"artifact": artifact,
"zero_ratio": stats.get("zero_ratio"),
"center_patch_zero_ratio": stats.get("center_patch_zero_ratio"),
"overlap_ratio": None,
"center_patch_overlap_ratio": None,
}
)
lt0 = payload["lt0"]
rows.append(
{
"root": result["root"],
"date": slave_date,
"artifact": "lt0",
"zero_ratio": lt0.get("zero_pair_ratio"),
"center_patch_zero_ratio": lt0.get("center_patch_zero_pair_ratio"),
"overlap_ratio": lt0.get("valid_pair_ratio"),
"center_patch_overlap_ratio": lt0.get("center_patch_valid_pair_ratio"),
}
)
overlap = payload["mli0_samp_overlap"]
rows.append(
{
"root": result["root"],
"date": slave_date,
"artifact": "mli0_samp_overlap",
"zero_ratio": None,
"center_patch_zero_ratio": None,
"overlap_ratio": overlap.get("overlap_nonzero_ratio"),
"center_patch_overlap_ratio": overlap.get("center_patch_overlap_nonzero_ratio"),
}
)
return rows
def write_summary_tsv(path: Path, rows: list[dict[str, Any]]) -> None:
header = [
"root",
"date",
"artifact",
"zero_ratio",
"center_patch_zero_ratio",
"overlap_ratio",
"center_patch_overlap_ratio",
]
lines = ["\t".join(header)]
for row in rows:
values = []
for key in header:
value = row.get(key)
if isinstance(value, float):
values.append(f"{value:.6f}")
elif value is None:
values.append("")
else:
values.append(str(value))
lines.append("\t".join(values))
path.write_text("\n".join(lines) + "\n", encoding="utf-8")
def audit_root(run_root: Path, master_date: str, slave_dates: tuple[str, ...], project: str) -> dict[str, Any]:
base_script = Path(__file__).with_name("audit_lt1_dem_geometry_chain.py")
base = load_base_module(base_script)
project_root = run_root / project
dem_dir = project_root / "DEM"
out_root = run_root / "audit_dem_geometry"
out_root.mkdir(parents=True, exist_ok=True)
master_shape = base.parse_gamma_shape(dem_dir / f"{master_date}_2rlks.amp.par")
hgtsim = base.read_float32_image(dem_dir / f"{master_date}_2rlks.rdc.dem", master_shape)
result: dict[str, Any] = {
"root": str(run_root),
"project": project,
"master_date": master_date,
"master_shape": {"width": master_shape.width, "lines": master_shape.lines},
"dem": {
"hgtsim": base.summarize_array(hgtsim),
},
"slaves": {},
}
base.write_quicklook(out_root / "hgtsim.pgm", hgtsim)
lt0_quicklook_written = False
for slave_date in slave_dates:
slc_dir = project_root / "SLC" / slave_date
rslc_dir = project_root / "RSLC" / slave_date
slave_shape = base.parse_gamma_shape(slc_dir / f"{slave_date}_2rlks.amp.par")
samp = base.read_float32_image(slc_dir / f"{slave_date}_2rlks.amp", slave_shape)
mli0 = base.read_float32_image(rslc_dir / "mli0", slave_shape)
lt0 = base.read_lt0_lookup(rslc_dir / "lt0", master_shape)
lt0_mag = (lt0[:, :, 0].astype("float64") ** 2 + lt0[:, :, 1].astype("float64") ** 2) ** 0.5
slave_out = out_root / slave_date
slave_out.mkdir(parents=True, exist_ok=True)
base.write_quicklook(slave_out / "samp.pgm", samp)
base.write_quicklook(slave_out / "mli0.pgm", mli0)
if not lt0_quicklook_written:
base.write_quicklook(out_root / "lt0_magnitude.pgm", lt0_mag.astype("float32"))
lt0_quicklook_written = True
slave_summary = {
"shape": {"width": slave_shape.width, "lines": slave_shape.lines},
"samp": base.summarize_array(samp),
"mli0": base.summarize_array(mli0),
"lt0": base.summarize_lt0(lt0),
"mli0_samp_overlap": base.summarize_overlap(mli0, samp),
}
result["slaves"][slave_date] = slave_summary
(slave_out / "summary.json").write_text(
json.dumps(slave_summary, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8",
)
(out_root / "summary.json").write_text(
json.dumps(result, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8",
)
rows = build_summary_rows(result)
write_summary_tsv(out_root / "audit_summary.tsv", rows)
return result
def main() -> int:
if len(sys.argv) < 4:
print(
"usage: audit_lt1_pool_multiscene_root.py <run_root> <master_date> <slave_date> [slave_date ...] [--project name]",
file=sys.stderr,
)
return 2
args = list(sys.argv[1:])
project = "pyint_stage"
if "--project" in args:
idx = args.index("--project")
try:
project = args[idx + 1]
except IndexError as exc:
raise SystemExit("--project requires a value") from exc
del args[idx : idx + 2]
run_root = Path(args[0]).resolve()
master_date = args[1]
slave_dates = tuple(args[2:])
result = audit_root(run_root, master_date, slave_dates, project)
print(
json.dumps(
{
"run_root": str(run_root),
"output_dir": str(run_root / "audit_dem_geometry"),
"master_date": master_date,
"slave_count": len(slave_dates),
"project": project,
},
ensure_ascii=False,
)
)
return 0
if __name__ == "__main__":
raise SystemExit(main())
+118
View File
@@ -0,0 +1,118 @@
#!/usr/bin/env bash
set -euo pipefail
if [ $# -lt 1 ]; then
echo "usage: $0 YYYYMMDD" >&2
exit 1
fi
DATE_TEXT="$1"
ROOT='/mnt/d/PyINT_POOL_TEST/LT1A_MONO_SYC_STRIP1_E129.6_N45.0_3scene'
PROJECT_DIR="$ROOT/pyint_stage"
DOWNLOAD_DIR="$PROJECT_DIR/DOWNLOAD"
CURRENT_SLC_DIR="$PROJECT_DIR/SLC/$DATE_TEXT"
COMPARE_ROOT="$ROOT/import_compare/$DATE_TEXT"
LIST_FILE="$COMPARE_ROOT/t_$DATE_TEXT"
CURRENT_PAR="$CURRENT_SLC_DIR/$DATE_TEXT.slc.par"
GAMMA_ENV='/mnt/d/Code/Insar_management_system_v2/backend/app/pyint_pipeline/pyint_gamma_env.sh'
die() {
echo "$1" >&2
exit 1
}
[ -f "$CURRENT_PAR" ] || die "Current .slc.par not found: $CURRENT_PAR"
[ -f "$GAMMA_ENV" ] || die "Gamma env script not found: $GAMMA_ENV"
SCENE_TIFF="$(find "$DOWNLOAD_DIR" -maxdepth 1 -type f -name "LT1*${DATE_TEXT}*.tiff" | sort | head -n 1)"
[ -n "$SCENE_TIFF" ] || die "Scene TIFF not found for date: $DATE_TEXT"
. "$GAMMA_ENV" >/dev/null 2>&1
mkdir -p "$COMPARE_ROOT"
printf '%s\n' "$SCENE_TIFF" >"$LIST_FILE"
pushd "$COMPARE_ROOT" >/dev/null
SCENE_XML="${SCENE_TIFF%.tiff}.meta.xml"
[ -f "$SCENE_XML" ] || die "Scene meta xml not found: $SCENE_XML"
par_LT1_SLC "$SCENE_TIFF" "$SCENE_XML" "./$DATE_TEXT.slc.par" "./$DATE_TEXT.slc" > import.stdout.log 2> import.stderr.log
par_LT1_SLC_YSLi "$SCENE_TIFF" "$SCENE_XML" "./$DATE_TEXT.slc.update" "./$DATE_TEXT.slc.update.par" 0 >> import.stdout.log 2>> import.stderr.log
popd >/dev/null
ALT_PAR="$COMPARE_ROOT/$DATE_TEXT.slc.par"
[ -f "$ALT_PAR" ] || die "Alternate .slc.par not found: $ALT_PAR"
python3 - "$ALT_PAR" "$COMPARE_ROOT/$DATE_TEXT.slc.update.par" <<'PY'
import sys
from pathlib import Path
main_path = Path(sys.argv[1])
update_path = Path(sys.argv[2])
main_lines = main_path.read_text(encoding="utf-8", errors="ignore").splitlines()
update_lines = update_path.read_text(encoding="utf-8", errors="ignore").splitlines()
prefixes = ("number_of_state_vectors:", "time_of_first_state_vector:", "state_vector_interval:", "state_vector_position_", "state_vector_velocity_")
main_prefix = ("number_of_state_vectors:", "time_of_first_state_vector:", "state_vector_interval:", "state_vector_position_", "state_vector_velocity_")
filtered_main = [line for line in main_lines if not line.startswith(main_prefix)]
replacement = [line for line in update_lines if line.startswith(prefixes)]
main_path.write_text("\n".join(filtered_main + replacement) + "\n", encoding="utf-8")
PY
python3 - "$CURRENT_PAR" "$ALT_PAR" <<'PY'
import re
import sys
from pathlib import Path
keys = [
"center_latitude",
"center_longitude",
"start_time",
"center_time",
"end_time",
"azimuth_line_time",
"range_samples",
"azimuth_lines",
"range_pixel_spacing",
"azimuth_pixel_spacing",
"near_range_slc",
"center_range_slc",
"far_range_slc",
"incidence_angle",
"heading",
"prf",
"azimuth_proc_bandwidth",
"doppler_polynomial",
"number_of_state_vectors",
"time_of_first_state_vector",
"state_vector_interval",
]
vector_patterns = [
"state_vector_position_1",
"state_vector_velocity_1",
"state_vector_position_2",
"state_vector_velocity_2",
"state_vector_position_3",
"state_vector_velocity_3",
]
def read_map(path: Path):
data = {}
for line in path.read_text(encoding="utf-8", errors="ignore").splitlines():
for key in keys + vector_patterns:
if line.startswith(key + ":"):
data[key] = line.split(":", 1)[1].strip()
break
return data
cur = read_map(Path(sys.argv[1]))
alt = read_map(Path(sys.argv[2]))
all_keys = keys + vector_patterns
for key in all_keys:
cur_v = cur.get(key, "")
alt_v = alt.get(key, "")
if cur_v != alt_v:
print(f"{key}\n current: {cur_v}\n alt: {alt_v}")
PY
@@ -0,0 +1 @@
2025 6 23 13 34 55.000 -1307508.7503 -651238.6465 -6835090.2734 2779.6665514 6982.8147436 -12.1250000
@@ -0,0 +1 @@
2025 6 23 13 34 55.000 -1307508.7503 -651238.6465 -6835090.2734 2779.6665514 6982.8147436 -12.1250000
@@ -0,0 +1 @@
2025 6 23 13 34 55.000 -1307508.7503 -651238.6465 -6835090.2734 2779.6665514 6982.8147436 -12.1250000
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
@@ -0,0 +1,99 @@
# PyINT
[![Language](https://img.shields.io/badge/python-3.5%2B-blue.svg)](https://www.python.org/)
[![License](https://img.shields.io/badge/license-GPL-yellow.svg)](https://github.com/ymcmrs/PyINT/blob/master/LICENSE)
### Single or time-series of interferograms processing based on python and GAMMA for all of the present SAR datasets.
PYthon-based INterferometry Toolbox (PyINT) is an open-source package for single or time-series of interferograms processing from downloading data (or SLC) to generating differential-unwrapped interferograms by using GAMMA software. You can process in a routine way (e.g., raw2ifg.py, slc2ifg.py or pyintApp.py) or process step by step. There are many GAMMA-independent tools of PyINT could be useful for you no matter you use GAMMA or other interferometry softwares (e.g., ISCE, SNAP). Advantages include (but not limited to) download and update precise-orbit data automatically (support S1, ERS, ASAR), download and process 30m-SRTM dem automatically, cat multi-frames automatically, select swaths and bursts flexibly (for S1), extract the related S1 butsts for Coregistration automatically, etc. Welcome to contribute/improve PyINT.
### 1 Download
Download the development version using git:
cd ~/python
git clone https://github.com/ymcmrs/PyINT
### 2 Installation
1) To make pyint importable in python, by adding the path PyINT directory to your $PYTHONPATH
For csh/tcsh user, add to your **_~/.cshrc_** file for example:
############################ Python ###############################
if ( ! $?PYTHONPATH ) then
setenv PYTHONPATH ""
endif
##--------- Anaconda ---------------##
setenv PYTHON3DIR ~/python/anaconda3
setenv PATH ${PATH}:${PYTHON3DIR}/bin
##--------- PyINT ------------------##
setenv PYINT_HOME ~/python/PyINT
setenv PYTHONPATH ${PYTHONPATH}:${PYINT_HOME}
setenv PATH ${PATH}:${PYINT_HOME}/pyint
2) Install gdal, elevation module using pip or conda for DEM processing.
3) Install [SSARA](https://github.com/bakerunavco/SSARA) and set account info for downloading data. [option]
### 3 Running PyINT
1). $SCRATCHDIR and $TEMPLATEDIR should be available in your system environment. $SCRATCHDIR for processing, $TEMPLATEDIR for template files to set the related processing parameters, $DEMDIR for saving DEMs:
setenv SCRATCHDIR /Users/Yunmeng/Documents/SCRATCH
setenv TEMPLATEDIR /Users/Yunmeng/Documents/development/TEMPLATEDIR
setenv DEMDIR /Users/Yunmeng/Documents/SCRATCH/DEM
2). Preparing your template file, which should be saved in $TEMPLATEDIR, for setting some basic parameters (see the template file above).The template file should be named with a prefix of your project name:
e.g., MexicoCityT143F529S1D.template [Region + Track + Frame + Satellite + Orbit]
3). Single interferogram processing:
slc2ifg.py projectName Mdate Sdate # start from SLC to unwrapped-differential Ifg
raw2ifg.py projectName Mdate Sdate # start from raw data to unwrapped-differential Ifg
e.g. :
slc2ifg.py HawaiiT87F526S1D 20150101 20160201
raw2ifg.py HawaiiT87F526S1D 20150101 20160201
4). Time-series of interferograms processing.
pyintApp.py projectName
e.g. :
pyintApp.py MexicoCityT143F529S1D # template file MexicoCityT143F529S1D.template should be availabe in TEMPLATEDIR
General work-flow:
1) download data : download SLCs using SSARA (please check https://github.com/bakerunavco/SSARA)
[You should provide Sensor, Track, Frame, or Time information in template]
2) generate SLC : raw 2 slc (multi-frame processing is also supported)
[include orbit correction for S1,ASAR,ERS and burst-extraction for S1]
3) generate DEM : reference image related geo-dem, rdc-dem, lookup table will be generated.
[SRTM-1 will be downloaded and processed automatically if not provided]
4) coregister SLC : coregister SLCs to the reference SLC iamge.
[with assistant of DEM]
5) select pairs : select interferometric pairs for time-series processing.
[networks of sbas, sequential, delaunay, and stars are supported]
6) interferometry : generate unwrapped differential interferograms.
[include differential, unwrapping, and geocoding]
7) load data : loading data for time-series analysis, mintPy is supported presently.
Note:
i ) Single interferogram processing please use slc2ifg.py or raw2ifg.py
ii ) Multi-processor parallel processing is supported, but keep in mind GAMMA calls multi-threads already.
iii) You can using pyintApp.py from downloading data to generate time-series of unwrapped-differential Ifgs,
or you also can process step by step.
Note: All of the above codes are based on the hypothesis that you have installed [GAMMA](https://www.gamma-rs.ch/).
### 4 Citing this work
Y.M., Cao, "PyINT: Python&GAMMA based interferometry toolbox", Remote Sensing Code Library, doi:10.21982/vd48-7p51, April, 2019.
@@ -0,0 +1,12 @@
# Vendored PyINT
- Source copied from local path: `D:\Code\PyINT`
- Vendored into this repository on: `2026-04-19`
- Scope kept in repo: `pyint/`, `template/`, `README.md`, `LICENSE`
- Excluded from vendored copy: `pyint_bk/`, `pyint.zip`, IDE metadata, `__pycache__`
Notes:
- This vendored copy is used by the local D-InSAR `PyINT / Gamma` integration.
- Runtime defaults now resolve `PYINT_HOME` to this directory when `.env` does not override it.
- If upstream `PyINT` is updated, sync this directory intentionally and record the source revision or date here.
@@ -0,0 +1,81 @@
Gamma Interferometric SAR Processor (ISP) - Image Parameter File
title: s1a-iw1-slc-vv-20210110t110734-20210110t110759-036075-043a78-004.tiff S1A-IW-IW1-VV-36075 (software: Sentinel-1 IPF 003.31)
sensor: S1A IW IW1 VV
date: 2021 01 10 11 07 33.60437
start_time: 40053.604372 s
center_time: 40067.080599 s
end_time: 40080.556826 s
azimuth_line_time: 2.05555630e-03 s
line_header_size: 0
range_samples: 68467
azimuth_lines: 13113
range_looks: 1
azimuth_looks: 1
image_format: FCOMPLEX
image_geometry: SLANT_RANGE
polarization: VV
range_scale_factor: 1.0000000e+00
azimuth_scale_factor: 1.0000000e+00
center_latitude: 25.7907364 degrees
center_longitude: 104.4737803 degrees
heading: -12.5014428 degrees
range_pixel_spacing: 2.3295620 m
azimuth_pixel_spacing: 13.9946500 m
near_range_slc: 798980.1369 m
center_range_slc: 878728.0328 m
far_range_slc: 958475.9288 m
first_slant_range_polynomial: 0.00000 0.00000 0.00000e+00 0.00000e+00 0.00000e+00 0.00000e+00 s m 1 m^-1 m^-2 m^-3
center_slant_range_polynomial: 0.00000 0.00000 0.00000e+00 0.00000e+00 0.00000e+00 0.00000e+00 s m 1 m^-1 m^-2 m^-3
last_slant_range_polynomial: 0.00000 0.00000 0.00000e+00 0.00000e+00 0.00000e+00 0.00000e+00 s m 1 m^-1 m^-2 m^-3
incidence_angle: 39.6640 degrees
azimuth_deskew: ON
azimuth_angle: 90.0000 degrees
radar_frequency: 5.4050005e+09 Hz
adc_sampling_rate: 6.4345241e+07 Hz
chirp_bandwidth: 5.6500000e+07 Hz
prf: 486.4863103 Hz
azimuth_proc_bandwidth: 327.00000 Hz
doppler_polynomial: 17.39054 -2.62817e-05 -8.00473e-11 0.00000e+00 Hz Hz/m Hz/m^2 Hz/m^3
doppler_poly_dot: 0.00000e+00 0.00000e+00 0.00000e+00 0.00000e+00 Hz/s Hz/s/m Hz/s/m^2 Hz/s/m^3
doppler_poly_ddot: 0.00000e+00 0.00000e+00 0.00000e+00 0.00000e+00 Hz/s^2 Hz/s^2/m Hz/s^2/m^2 Hz/s^2/m^3
receiver_gain: 0.0000 dB
calibration_gain: 0.0000 dB
sar_to_earth_center: 7072935.2710 m
earth_radius_below_sensor: 6374216.3707 m
earth_semi_major_axis: 6378137.0000 m
earth_semi_minor_axis: 6356752.3141 m
number_of_state_vectors: 15
time_of_first_state_vector: 40002.000000 s
state_vector_interval: 10.000000 s
state_vector_position_1: -1202502.7493 6500810.8061 2515842.3001 m m m
state_vector_velocity_1: 2079.47309 -2309.53890 6932.46052 m/s m/s m/s
state_vector_position_2: -1181658.0158 6477336.1615 2585023.4928 m m m
state_vector_velocity_2: 2089.41624 -2385.34851 6903.64775 m/s m/s m/s
state_vector_position_3: -1160715.5736 6453104.6806 2653912.6562 m m m
state_vector_velocity_3: 2099.01470 -2460.90464 6874.05521 m/s m/s m/s
state_vector_position_4: -1139678.8732 6428118.9436 2722502.0093 m m m
state_vector_velocity_4: 2108.26777 -2536.19825 6843.68628 m/s m/s m/s
state_vector_position_5: -1118551.3718 6402381.6207 2790783.8056 m m m
state_vector_velocity_5: 2117.17479 -2611.22032 6812.54442 m/s m/s m/s
state_vector_position_6: -1097336.5330 6375895.4722 2858750.3336 m m m
state_vector_velocity_6: 2125.73515 -2685.96187 6780.63319 m/s m/s m/s
state_vector_position_7: -1076037.8261 6348663.3481 2926393.9175 m m m
state_vector_velocity_7: 2133.94831 -2760.41395 6747.95623 m/s m/s m/s
state_vector_position_8: -1054658.7259 6320688.1875 2993706.9187 m m m
state_vector_velocity_8: 2141.81376 -2834.56766 6714.51728 m/s m/s m/s
state_vector_position_9: -1033202.7115 6291973.0188 3060681.7361 m m m
state_vector_velocity_9: 2149.33106 -2908.41412 6680.32013 m/s m/s m/s
state_vector_position_10: -1011673.2665 6262520.9586 3127310.8074 m m m
state_vector_velocity_10: 2156.49982 -2981.94447 6645.36870 m/s m/s m/s
state_vector_position_11: -990073.8782 6232335.2122 3193586.6096 m m m
state_vector_velocity_11: 2163.31969 -3055.14991 6609.66698 m/s m/s m/s
state_vector_position_12: -968408.0367 6201419.0725 3259501.6599 m m m
state_vector_velocity_12: 2169.79039 -3128.02167 6573.21903 m/s m/s m/s
state_vector_position_13: -946679.2350 6169775.9199 3325048.5169 m m m
state_vector_velocity_13: 2175.91169 -3200.55102 6536.02901 m/s m/s m/s
state_vector_position_14: -924890.9683 6137409.2222 3390219.7811 m m m
state_vector_velocity_14: 2181.68339 -3272.72926 6498.10116 m/s m/s m/s
state_vector_position_15: -903046.7331 6104322.5337 3455008.0956 m m m
state_vector_velocity_15: 2187.10536 -3344.54774 6459.43982 m/s m/s m/s
@@ -0,0 +1,494 @@
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
###########################################################################
# Header information
###########################################################################
"""API_download_S1_SLC.py: Script to download Sentinel-1 SLC images from the ASF mirror
Supports both bounding box and Shapefile for spatial filtering"""
__author__ = "Alexis Hrysiewicz"
__copyright__ = "Copyright 2022"
__credits__ = ["Alexis Hrysiewicz"]
__license__ = "GPL"
__version__ = "2.0.0"
__maintainer__ = "Alexis Hrysiewicz"
__status__ = "Production"
__date__ = "Jan. 2022"
###########################################################################
# Python packages
###########################################################################
import os
import sys
import pandas as pd
import datetime
import os.path
import optparse
# 尝试导入 geopandas 和 shapely 用于 Shapefile 支持
try:
import geopandas as gpd
from shapely.geometry import box, Polygon, MultiPolygon
HAS_SHAPEFILE_SUPPORT = True
except ImportError:
HAS_SHAPEFILE_SUPPORT = False
print("Warning: geopandas/shapely not installed. Shapefile support disabled.")
print("Install with: pip install geopandas shapely")
###########################################################################
###########################################################################
class OptionParser (optparse.OptionParser):
def check_required(self, opt):
option = self.get_option(opt)
if getattr(self.values, option.dest) is None:
self.error("%s option not supplied" % option)
def bbox_from_shapefile(shapefile_path):
"""
从 Shapefile 文件提取边界框
Args:
shapefile_path: Shapefile 文件路径(.shp)
Returns:
边界框字符串格式: "min_lon,min_lat,max_lon,max_lat"
"""
try:
# 读取 Shapefile
gdf = gpd.read_file(shapefile_path)
# 计算总边界框
total_bounds = gdf.total_bounds
# total_bounds = (minx, miny, maxx, maxy)
# 转换为字符串格式
bbox_str = f"{total_bounds[0]},{total_bounds[1]},{total_bounds[2]},{total_bounds[3]}"
print(f"Shapefile bounding box: {bbox_str}")
return bbox_str
except Exception as e:
print(f"Error reading shapefile: {str(e)}")
return None
def check_slc_exists(slc_name, path_SLC, path_RSLC, acquisition_date):
"""
检查 SLC 文件是否已存在
Args:
slc_name: SLC 文件名
path_SLC: SLC 存储路径
path_RSLC: RSLC 存储路径
acquisition_date: 采集日期字符串
Returns:
bool: 文件是否已存在
"""
# 检查 .zip 文件
if os.path.exists(os.path.join(path_SLC, slc_name + '.zip')):
return True
# 检查 .rslc 文件
try:
datei = datetime.datetime.strptime(acquisition_date.split('.')[0], '%Y-%m-%dT%H:%M:%S').strftime("%Y%m%d")
if os.path.exists(os.path.join(path_RSLC, datei + '.vv.rslc')):
return True
except:
pass
return False
def read_netrc(machine_name):
"""
从 ~/.netrc 文件读取登录凭证
Args:
machine_name: 机器名称 (例如: urs.earthdata.nasa.gov)
Returns:
tuple: (username, password) 或 (None, None) 如果未找到
"""
netrc_path = os.path.expanduser('~/.netrc')
if not os.path.exists(netrc_path):
return None, None
try:
with open(netrc_path, 'r') as f:
lines = f.readlines()
i = 0
while i < len(lines):
line = lines[i].strip()
# 查找 machine 行
if line.startswith('machine ' + machine_name):
username = None
password = None
# 查找接下来的几行中的 login 和 password
j = i + 1
while j < len(lines) and j < i + 5: # 最多查找5行
next_line = lines[j].strip()
tokens = next_line.split()
if len(tokens) >= 2:
if tokens[0] == 'login':
username = tokens[1]
elif tokens[0] == 'password':
password = tokens[1]
# 如果找到下一个 machine,停止查找
if next_line.startswith('machine '):
break
j += 1
if username and password:
return username, password
i += 1
except Exception as e:
print(f"Warning: Error reading .netrc file: {str(e)}")
return None, None
def download_slc(url, username, password, path_SLC):
"""
下载单个 SLC 文件
Args:
url: 下载 URL
username: ASF 用户名
password: ASF 密码
path_SLC: 存储路径
Returns:
bool: 下载是否成功
"""
# 如果提供了用户名和密码,使用它们
if username and password:
cmd = f'wget -c --http-user={username} --http-password={password} "{url}" -P {path_SLC}'
else:
# 否则使用 .netrc 文件
# --auth-no-challenge: 立即发送认证信息,不等待服务器挑战
# --netrc: 从 ~/.netrc 读取认证信息
cmd = f'wget -c --auth-no-challenge --netrc "{url}" -P {path_SLC}'
return os.system(cmd) == 0
def convert_yyyymmdd_to_iso(date_str):
"""
将 YYYYMMDD 格式转换为 ISO 格式 (YYYY-MM-DDTHH:MM:SS)
Args:
date_str: 日期字符串 (YYYYMMDD)
Returns:
str: ISO 格式日期字符串 (YYYY-MM-DDT00:00:00)
"""
if len(date_str) == 8:
year = date_str[0:4]
month = date_str[4:6]
day = date_str[6:8]
return f"{year}-{month}-{day}T00:00:00"
else:
# 如果已经是其他格式,直接返回
return date_str
###########################################################################
###########################################################################
if len(sys.argv) < 3:
prog = os.path.basename(sys.argv[0])
print("="*80)
print("Sentinel-1 SLC Downloader from ASF")
print("="*80)
print("\nUsage examples:")
print("\n1. Using bounding box:")
print(" python3 " + prog + " -u username -p password -s . -r . \\")
print(" -b -10.78,51.27,-5.03,55.70 \\")
print(" -i 20170101 -j 20231231 \\")
print(f" -o 1 -f a -q IW -m csv -w n")
print("\n2. Using Shapefile (new feature):")
print(" python3 " + prog + " -u username -p password -s . -r . \\")
print(" --shp study_area.shp \\")
print(" -i 20170101 -j 20231231 \\")
print(f" -o 1 -f a -q IW -m csv -w n")
print("\nOptions:")
print(" -u, --username ASF username (optional, can use .netrc)")
print(" -p, --password ASF password (optional, can use .netrc)")
print(" -n, --netrc Machine name in ~/.netrc (default: urs.earthdata.nasa.gov)")
print(" -s, --path_SLC Output directory for SLC files")
print(" -r, --path_RSLC Directory to check for processed RSLC files")
print(" -b, --bbox Bounding box (min_lon,min_lat,max_lon,max_lat)")
print(" --shp Shapefile path (.shp) for spatial filtering")
print(" -i, --date_start Start date (YYYYMMDD)")
print(" -j, --date_end End date (YYYYMMDD)")
print(" -o, --orbit_relative Relative orbit number (optional)")
print(" --frame Frame number (optional)")
print(" -f, --flight_direction Flight direction (a=ascending, d=descending, or all)")
print(" -q, --q_acqui_mode Acquisition mode (IW, EW, SM, or all)")
print(" -m, --mode Output format (csv or kml)")
print(" -w, --write Download files? (Y/N)")
print(" --parallel Number of parallel downloads (default: 1, serial)")
print("\nNote: Shapefile support requires geopandas and shapely")
print("="*80)
sys.exit(-1)
else:
usage = "usage: %prog [options] "
parser = OptionParser(usage=usage)
parser.add_option("-u", "--username", action="store", type="string", default=None,
help="ASF username (can be read from ~/.netrc)")
parser.add_option("-p", "--password", action="store", type="string", default=None,
help="ASF password (can be read from ~/.netrc)")
parser.add_option("-n", "--netrc", action="store", type="string", default='urs.earthdata.nasa.gov',
help="Machine name in ~/.netrc file (default: urs.earthdata.nasa.gov)")
parser.add_option("-s", "--path_SLC", action="store", type="string", default='.')
parser.add_option("-r", "--path_RSLC", action="store", type="string", default='.') # Only available for GAMMA stack
parser.add_option("-b", "--bbox", action="store", type="string", default='-10.78,51.27,-5.03,55.70')
parser.add_option("--shp", "--shapefile", action="store", type="string", default=None,
help="Shapefile path for spatial filtering")
parser.add_option("-i", "--date_start", action="store", type="string", default='20170101')
parser.add_option("-j", "--date_end", action="store", type="string", default='20240101')
parser.add_option("-o", "--orbit_relative", action="store", type="float", default=None,
help="Relative orbit number (optional, if not specified will search all orbits)")
parser.add_option("--frame", action="store", type="int", default=None,
help="Frame number (optional, if not specified will search all frames)")
parser.add_option("-f", "--flight_direction", action="store", type="string", default='a',
help="Flight direction (a=ascending, d=descending, or 'all' for both)")
parser.add_option("-q", "--q_acqui_mode", action="store", type="string", default='IW')
parser.add_option("-m", "--mode", action="store", type="string", default='csv')
parser.add_option("-w", "--write", action="store", type="string", default='n')
parser.add_option("--parallel", action="store", type="int", default=1,
help="Number of parallel downloads (default: 1, serial)")
(options, args) = parser.parse_args()
###########################################################################
# Main
###########################################################################
date_format = "%Y-%m-%d"
# 转换日期格式
date_start_iso = convert_yyyymmdd_to_iso(options.date_start)
date_end_iso = convert_yyyymmdd_to_iso(options.date_end)
# 处理用户名和密码:如果未提供,尝试从 .netrc 读取
if options.username is None or options.password is None:
netrc_username, netrc_password = read_netrc(options.netrc)
if netrc_username and netrc_password:
if options.username is None:
options.username = netrc_username
print(f"Username read from ~/.netrc ({options.netrc})")
if options.password is None:
options.password = netrc_password
print(f"Password read from ~/.netrc ({options.netrc})")
else:
if options.username is None:
print("Error: Username not provided and not found in ~/.netrc")
print("Please provide username with -u option or configure ~/.netrc")
sys.exit(1)
if options.password is None:
print("Error: Password not provided and not found in ~/.netrc")
print("Please provide password with -p option or configure ~/.netrc")
sys.exit(1)
# 处理空间范围:优先使用 Shapefile,否则使用 bounding box
if options.shp:
if not HAS_SHAPEFILE_SUPPORT:
print("Error: Shapefile support requires geopandas and shapely")
print("Install with: pip install geopandas shapely")
sys.exit(1)
print(f"Using Shapefile: {options.shp}")
bbox = bbox_from_shapefile(options.shp)
if bbox is None:
print("Error: Failed to extract bounding box from shapefile")
sys.exit(1)
else:
bbox = options.bbox
print(f"Using bounding box: {bbox}")
# 构建 API 查询命令
# 轨道号、frame 和飞行方向都是可选的
api_params = f"platform=s1&bbox={bbox}&start={date_start_iso}-UTC&end={date_end_iso}-UTC&processingLevel=SLC&maxResults=10000"
# 如果指定了轨道号,添加到查询参数
if options.orbit_relative is not None:
api_params += f"&relativeOrbit={int(options.orbit_relative)}"
# 如果指定了 frame 号,添加到查询参数
if hasattr(options, 'frame') and options.frame is not None:
api_params += f"&frame={options.frame}"
# 如果指定了飞行方向且不是 'all',添加到查询参数
if options.flight_direction and options.flight_direction.upper() != 'ALL':
api_params += f"&flightDirection={options.flight_direction.upper()}"
# 添加输出格式
api_params += f"&output={options.mode.upper()}"
cmd1 = f'curl "https://api.daac.asf.alaska.edu/services/search/param?{api_params}" > SLC_list.{options.mode.lower()}'
print(f"Querying ASF API for SLC data...")
print(f" Bounding Box: {bbox}")
print(f" Date Range: {options.date_start} to {options.date_end}")
if options.orbit_relative is not None:
print(f" Orbit: {options.orbit_relative}")
else:
print(f" Orbit: All")
if hasattr(options, 'frame') and options.frame is not None:
print(f" Frame: {options.frame}")
else:
print(f" Frame: All")
if options.flight_direction and options.flight_direction.upper() != 'ALL':
print(f" Flight Direction: {options.flight_direction.upper()}")
else:
print(f" Flight Direction: All")
print(f" Mode: {options.q_acqui_mode.upper()}")
print()
# 执行查询
if options.mode.upper() == 'KML':
os.system(cmd1)
elif options.mode.upper() == 'CSV':
os.system(cmd1)
else:
print('Error: Please select a correct mode (csv or kml)...')
sys.exit(1)
# 根据波束模式过滤列表
print(f"Filtering results by acquisition mode: {options.q_acqui_mode.upper()}")
if os.path.exists("SLC_list.csv"):
os.rename("SLC_list.csv","SLC_list_orig.csv")
h = 0
fout = open("SLC_list.csv",'w')
total_count = 0
matched_count = 0
with open("SLC_list_orig.csv") as fi:
for li in fi:
total_count += 1
if h > 0:
if options.q_acqui_mode.upper() == 'all':
fout.write(li)
matched_count += 1
elif options.q_acqui_mode.upper() in li:
fout.write(li)
matched_count += 1
else:
fout.write(li)
h = h + 1
fout.close()
os.remove("SLC_list_orig.csv")
print(f" Total results: {total_count - 1}")
print(f" Filtered results: {matched_count}")
else:
print("Warning: SLC_list.csv not found")
sys.exit(1)
# 下载文件
if options.mode.upper() == 'CSV' and options.write.upper() == 'Y':
try:
listSLC = pd.read_csv("SLC_list.csv")
except Exception as e:
print(f"Error reading SLC_list.csv: {str(e)}")
sys.exit(1)
print(f"\nFound {len(listSLC)} SLC files to process")
print("="*80)
# 创建输出目录
if not os.path.exists(options.path_SLC):
os.makedirs(options.path_SLC)
print(f"Created output directory: {options.path_SLC}")
# 检查是否有并行参数
parallel_numb = getattr(options, 'parallel', 1)
if parallel_numb is None:
parallel_numb = 1
# 准备下载数据列表
download_tasks = []
skipped_tasks = []
for h, slci in enumerate(listSLC['Granule Name']):
url = listSLC['URL'][h]
acquisition_date = listSLC['Acquisition Date'][h]
# 检查文件是否已存在
if check_slc_exists(slci, options.path_SLC, options.path_RSLC, acquisition_date):
skipped_tasks.append((h+1, slci, "Already exists"))
else:
download_tasks.append((h+1, slci, url, acquisition_date))
print(f"Files to download: {len(download_tasks)}")
print(f"Files skipped (already exists): {len(skipped_tasks)}")
# 并行下载函数
def download_worker(task):
idx, slci, url, acquisition_date = task
print(f"\n[{idx}/{len(listSLC)}] Downloading: {slci}")
if download_slc(url, options.username, options.password, options.path_SLC):
print(f" Status: Download SUCCESS")
return (idx, slci, "SUCCESS")
else:
print(f" Status: Download FAILED")
return (idx, slci, "FAILED")
# 执行下载
downloaded = 0
failed = 0
if parallel_numb > 1 and len(download_tasks) > 0:
# 并行下载
from multiprocessing.pool import ThreadPool
print(f"\nStarting parallel download with {parallel_numb} workers...")
pool = ThreadPool(parallel_numb)
results = pool.map(download_worker, download_tasks)
pool.close()
pool.join()
# 统计结果
for result in results:
if result[2] == "SUCCESS":
downloaded += 1
else:
failed += 1
elif len(download_tasks) > 0:
# 串行下载
print("\nStarting serial download...")
for task in download_tasks:
result = download_worker(task)
if result[2] == "SUCCESS":
downloaded += 1
else:
failed += 1
# 打印摘要
print("\n" + "="*80)
print("DOWNLOAD SUMMARY")
print("="*80)
print(f"Total SLC files: {len(listSLC)}")
print(f"Downloaded: {downloaded}")
print(f"Skipped (already exists): {len(skipped_tasks)}")
print(f"Failed: {failed}")
print("="*80)
if failed > 0:
print(f"\nWarning: {failed} downloads failed. Check the output above for details.")
sys.exit(1)
elif options.mode.upper() == 'KML' and options.write.upper() == 'Y':
print('Please, select CSV mode to download..')
elif options.write.upper() != 'Y':
print(f"\nSLC list saved to: SLC_list.csv")
print("To download files, re-run with -w Y option")
@@ -0,0 +1,139 @@
#! /usr/bin/env python
#################################################################
### This program is part of PyINT v1.0 ###
### Copy Right (c): 2017, Yunmeng Cao ###
### Author: Yunmeng Cao ###
### Email : ymcmrs@gmail.com ###
### Univ. : Central South University & University of Miami ###
#################################################################
import numpy as np
import os
import sys
import subprocess
import getopt
import time
import glob
import argparse
import linecache
import datetime
def StrNum(S):
S = str(S)
if len(S)==1:
S='0' +S
return S
def UseGamma(inFile, task, keyword):
if task == "read":
f = open(inFile, "r")
while 1:
line = f.readline()
if not line: break
if line.count(keyword) == 1:
strtemp = line.split(":")
value = strtemp[1].strip()
return value
print("Keyword " + keyword + " doesn't exist in " + inFile)
f.close()
#########################################################################
INTRODUCTION = '''
#############################################################################
Copy Right(c): 2017-2019, Yunmeng Cao @PyINT v1.0
Correct ASAR orbit using precise DORIS data.
'''
EXAMPLE = '''
Usage:
ASAR_orb_cor.py projectName Date
Examples:
ASAR_orb_cor.py AqabaERSA 960101
##############################################################################
'''
def cmdLineParse():
parser = argparse.ArgumentParser(description='Download (and correct) precise ERS orbit data.',\
formatter_class=argparse.RawTextHelpFormatter,\
epilog=INTRODUCTION+'\n'+EXAMPLE)
parser.add_argument('projectName',help='project name')
parser.add_argument('date',help='date of the ERS data')
inps = parser.parse_args()
return inps
################################################################################
def main(argv):
total = time.time()
inps = cmdLineParse()
projectName = inps.projectName
DATE = inps.date
scratchDir = os.getenv('SCRATCHDIR')
templateDir = os.getenv('TEMPLATEDIR')
ASAROrbDir = os.getenv('ASARORBDIR')
slcDir = scratchDir + '/' + projectName + '/SLC'
projDir = scratchDir + '/' + projectName
if len(DATE)==8:
DATE8 = DATE
DATE6 = DATE[2:8]
else:
DATE8 = '20' + DATE
DATE6 = DATE
slcDir1 = slcDir + '/' + DATE6
slcpar = slcDir1 + '/' + DATE6 + '.slc.par'
Year = DATE8[0:4]
Month = DATE8[4:6]
Day = DATE8[6:8]
DATE1 = (datetime.date(int(Year),int(Month),int(Day)) + datetime.timedelta(days=-1)).strftime("%Y%m%d")
DATE2 = (datetime.date(int(Year),int(Month),int(Day)) + datetime.timedelta(days=1)).strftime("%Y%m%d")
os.chdir(ASAROrbDir)
call_str = 'ls > t0'
os.system(call_str)
call_str="grep " + DATE1 + " t0 | grep " + DATE2 + " >t01"
os.system(call_str)
AA= np.loadtxt('t01',dtype=np.str)
AA_file = ASAROrbDir + '/' + str(AA)
call_str = 'DORIS_vec ' + slcpar + ' ' + AA_file
os.system(call_str)
print("Using DORIS orbital data for %s is done." % DATE)
sys.exit(1)
if __name__ == '__main__':
main(sys.argv[:])
@@ -0,0 +1,125 @@
#! /usr/bin/env python
#################################################################
### This program is part of PyINT v1.0 ###
### Copy Right (c): 2017, Yunmeng Cao ###
### Author: Yunmeng Cao ###
### Email : ymcmrs@gmail.com ###
### Univ. : Central South University & University of Miami ###
#################################################################
import numpy as np
import os
import sys
import subprocess
import getopt
import time
import glob
import argparse
import linecache
def StrNum(S):
S = str(S)
if len(S)==1:
S='0' +S
return S
def UseGamma(inFile, task, keyword):
if task == "read":
f = open(inFile, "r")
while 1:
line = f.readline()
if not line: break
if line.count(keyword) == 1:
strtemp = line.split(":")
value = strtemp[1].strip()
return value
print("Keyword " + keyword + " doesn't exist in " + inFile)
f.close()
def is_number(s):
try:
int(s)
return True
except ValueError:
return False
#########################################################################
INTRODUCTION = '''
#############################################################################
Copy Right(c): 2017-2019, Yunmeng Cao @PyINT v1.0
Correct ASAR orbit using precise DORIS data.
'''
EXAMPLE = '''
Usage:
ASAR_orb_cor_all.py projectName
Examples:
ASAR_orb_cor_all.py AqabaERSA
##############################################################################
'''
def cmdLineParse():
parser = argparse.ArgumentParser(description='Download (and correct) precise ERS orbit data.',\
formatter_class=argparse.RawTextHelpFormatter,\
epilog=INTRODUCTION+'\n'+EXAMPLE)
parser.add_argument('projectName',help='project name')
inps = parser.parse_args()
return inps
################################################################################
def main(argv):
total = time.time()
inps = cmdLineParse()
projectName = inps.projectName
scratchDir = os.getenv('SCRATCHDIR')
templateDir = os.getenv('TEMPLATEDIR')
slcDir = scratchDir + '/' + projectName + '/SLC'
ListSLC = os.listdir(slcDir)
Datelist = []
SLCfile = []
SLCParfile = []
for kk in range(len(ListSLC)):
if ( is_number(ListSLC[kk]) and len(ListSLC[kk])==6 ): # if SAR date number is 8, 6 should change to 8.
DD=ListSLC[kk]
Year=int(DD[0:2])
Month = int(DD[2:4])
Day = int(DD[4:6])
Datelist.append(ListSLC[kk])
N = len(Datelist)
for i in range(N):
call_str = 'ERS_orb_cor.py ' + projectName + ' ' + Datelist[i]
print(call_str)
os.system(call_str)
print("Using DEFT orbital data for project %s is done." % projectName)
sys.exit(1)
if __name__ == '__main__':
main(sys.argv[:])
@@ -0,0 +1,122 @@
#! /usr/bin/env python
#################################################################
### This program is part of PyINT v1.0 ###
### Copy Right (c): 2017, Yunmeng Cao ###
### Author: Yunmeng Cao ###
### Email : ymcmrs@gmail.com ###
### Univ. : Central South University & University of Miami ###
#################################################################
import numpy as np
import os
import sys
import subprocess
import getopt
import time
import glob
import argparse
import linecache
import datetime
def StrNum(S):
S = str(S)
if len(S)==1:
S='0' +S
return S
def UseGamma(inFile, task, keyword):
if task == "read":
f = open(inFile, "r")
while 1:
line = f.readline()
if not line: break
if line.count(keyword) == 1:
strtemp = line.split(":")
value = strtemp[1].strip()
return value
print("Keyword " + keyword + " doesn't exist in " + inFile)
f.close()
#########################################################################
INTRODUCTION = '''
#############################################################################
Copy Right(c): 2017-2019, Yunmeng Cao @PyINT v1.0
Precise ENVISAT orbit data from Delft (http://www.deos.tudelft.nl/).
Correct the orbit parameters using DORIS_vec
'''
EXAMPLE = '''
Usage:
ASAR_orb_cor_par.py slc_par
Examples:
ASAR_orb_cor_par.py 960101.slc.par
##############################################################################
'''
def cmdLineParse():
parser = argparse.ArgumentParser(description='Download (and correct) precise ERS orbit data.',\
formatter_class=argparse.RawTextHelpFormatter,\
epilog=INTRODUCTION+'\n'+EXAMPLE)
parser.add_argument('slc_par',help='slc_par file.')
inps = parser.parse_args()
return inps
################################################################################
def main(argv):
total = time.time()
inps = cmdLineParse()
slcpar = inps.slc_par
ASAROrbDir = os.getenv('ASARORBDIR')
PATH =os.getcwd()
DATE = UseGamma(slcpar,'read','date:')
Year = str(int(DATE[0:4]))
Month = str(int(DATE[4:8]))
Day = str(int(DATE[8:12]))
DATE1 = (datetime.date(int(Year),int(Month),int(Day)) + datetime.timedelta(days=-1)).strftime("%Y%m%d")
DATE2 = (datetime.date(int(Year),int(Month),int(Day)) + datetime.timedelta(days=1)).strftime("%Y%m%d")
os.chdir(ASAROrbDir)
call_str = 'ls > t0'
os.system(call_str)
call_str="grep " + DATE1 + " t0 | grep " + DATE2 + " > t01"
os.system(call_str)
AA= np.loadtxt('t01',dtype=np.str)
AA_file = ASAROrbDir + '/' + str(AA)
os.chdir(PATH)
call_str = 'DORIS_vec ' + slcpar + ' ' + AA_file + ' 20'
os.system(call_str)
print("Using DORIS orbital data for %s is done." % slcpar)
sys.exit(1)
if __name__ == '__main__':
main(sys.argv[:])
@@ -0,0 +1,167 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# mac
.DS_Store
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
tests
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023 Fanchengyan
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,2 @@
# AutoGACOS
A Python library for automatically submitting and downloading GACOS data
@@ -0,0 +1,20 @@
# Minimal makefile for Sphinx documentation
#
# You can set these variables from the command line, and also
# from the environment for the first two.
SPHINXOPTS ?=
SPHINXBUILD ?= sphinx-build
SOURCEDIR = source
BUILDDIR = build
# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.PHONY: help Makefile
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
@@ -0,0 +1,6 @@
recommonmark
sphinx>=7
myst-parser
myst_nb
sphinx_rtd_theme
Jinja2
@@ -0,0 +1,32 @@
InSAR Datasets
==============
To automatically submit requests to the GACOS service, the user needs to provide
the coordinates of the area of interest and the acquisition dates and times of
the SAR images. We provide a set of classes to automatically retrieve the
those information from well known InSAR datasets.
Currently, the following InSAR Datasets are supported:
* :class:`.HyP3Dataset`
* :class:`.LiCSARDataset`
HyP3Dataset
-----------
.. autoclass:: gacos.HyP3Dataset
:members:
:undoc-members:
:member-order: bysource
:show-inheritance:
LiCSARDataset
-------------
.. autoclass:: gacos.LiCSARDataset
:members:
:undoc-members:
:member-order: bysource
:show-inheritance:
@@ -0,0 +1,11 @@
Python API Reference
====================
.. toctree::
datasets/datasets
submit/submit
@@ -0,0 +1,15 @@
Requests Submitter
==================
The GACOS limits the number of acquisition requests that can be submitted at a time.
This is to prevent the system from being overloaded. But, if you have a large number
of acquisition requests to submit, you can submit them in batches. We designed a
:class:`gacos.Submitter` class to help you submit the requests in batches. The
acquisitions will be split into batches which not exceed the 20 acquisitions per
request.
.. autoclass:: gacos.Submitter
:members:
:undoc-members:
:member-order: bysource
:show-inheritance:
@@ -0,0 +1,58 @@
# Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Project information -----------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information
project = "FanSAR"
copyright = "2023, Fancy"
author = "Fancy"
release = "v1.0"
# -- General configuration ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration
extensions = [
"myst_nb",
"sphinx.ext.autodoc",
"sphinx.ext.doctest",
"sphinx.ext.intersphinx",
"sphinx.ext.napoleon",
"sphinx.ext.todo",
]
source_suffix = {
".rst": "restructuredtext",
".md": "markdown",
".ipynb": "myst-nb",
}
# templates_path = ['_templates']
exclude_patterns = []
# to disable execution of notebooks
nb_execution_mode = "off"
nb_execution_excludepatterns = ["quickstart.ipynb"]
# -- Options for HTML output -------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output
html_theme = "sphinx_rtd_theme"
# html_static_path = ['_static']
# General information about the project.
project = "faninsar"
copyright = "2023, Fancy"
author = "Chengyan Fan"
video_enforce_extra_source = True
autodoc_default_options = {
"members": True,
"undoc-members": True,
"member-order": "bysource",
"special-members": "__init__",
":show-inheritance:": True,
}
@@ -0,0 +1,19 @@
=====================================
Welcome to AutoGACOS's documentation!
=====================================
Introduction
------------
.. toctree::
:maxdepth: 4
:caption: Contents:
intro
user_guide/quickstart
AutoGACOS API Reference <api/index>
terminology
@@ -0,0 +1,3 @@
Introduction
============
@@ -0,0 +1,27 @@
.. _terminology:
Terminology
===========
.. glossary::
Acquisition
A single SAR acquisition, and is expressed as ``datetime.datetime`` object.
Pair
A pair is a combination of two SAR acquisitions.
Pairs
A collection of pairs.
Loop
A loop
Loops
A collection of loops.
SBASNetwork
A collection of loops and pairs.
CRS
A coordinate reference system (CRS) is a coordinate-based local, regional or global system used to locate geographical entities. In FanInSAR, the CRS is handled by the ``rasterio`` package.
@@ -0,0 +1,635 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Quickstart for AutoGACOS\n",
"\n",
"**AutoGACOS** is a Python library for automatically submitting and downloading GACOS data"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"import gacos"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"path = \"/Volumes/Data/Hyp3/descending_roi\"\n",
"ds = gacos.HyP3Dataset(path)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"check all acquisition dates in Hyp3 dateset"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"DatetimeIndex(['2015-11-12 23:26:31', '2015-12-06 23:26:31',\n",
" '2015-12-30 23:26:30', '2016-01-23 23:26:29',\n",
" '2016-02-16 23:26:28', '2016-03-11 23:26:28',\n",
" '2016-04-04 23:26:29', '2016-04-28 23:26:30',\n",
" '2016-05-22 23:26:34', '2016-06-15 23:26:36',\n",
" ...\n",
" '2023-01-10 23:27:15', '2023-01-22 23:27:15',\n",
" '2023-02-03 23:27:15', '2023-02-15 23:27:14',\n",
" '2023-02-27 23:27:15', '2023-03-11 23:27:14',\n",
" '2023-03-23 23:27:14', '2023-04-04 23:27:15',\n",
" '2023-08-14 23:27:22', '2023-09-07 23:27:23'],\n",
" dtype='datetime64[ns]', length=204, freq=None)\n",
"Index(['20151112', '20151206', '20151230', '20160123', '20160216', '20160311',\n",
" '20160404', '20160428', '20160522', '20160615',\n",
" ...\n",
" '20230110', '20230122', '20230203', '20230215', '20230227', '20230311',\n",
" '20230323', '20230404', '20230814', '20230907'],\n",
" dtype='object', length=204)\n",
"['23:25' '23:26' '23:27']\n"
]
}
],
"source": [
"print(ds.date_times)\n",
"print(ds.dates)\n",
"print(ds.times)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Submit GACOS requests automatically"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "bf9575b9deea497089cc8167b8c8a438",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
" 0%| | 0/3 [00:00<?, ?it/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "a9dafb6856a5407da0dbf6b965189f73",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
" 0%| | 0/1 [00:00<?, ?it/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
">>> succeed post: {'N': 39.16527884776772, 'W': 98.34602960014247, 'S': 38.52041942953548, 'E': 99.41788862899489, 'H': 23, 'M': 25, 'date': '20161007\\n20161031\\n20161124\\n20161218\\n20170111\\n20170204', 'type': '2', 'email': 'fanchengyan2020@126.com'}\n",
" sleeping for 546 seconds...\n"
]
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "8fd9eb9543774f3b87058eef331792df",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
" 0%| | 0/6 [00:00<?, ?it/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
">>> succeed post: {'N': 39.16527884776772, 'W': 98.34602960014247, 'S': 38.52041942953548, 'E': 99.41788862899489, 'H': 23, 'M': 26, 'date': '20151112\\n20151206\\n20151230\\n20160123\\n20160216\\n20160311\\n20160404\\n20160428\\n20160522\\n20160615\\n20160709\\n20160802\\n20160826\\n20160919\\n20170222\\n20170318\\n20170330', 'type': '2', 'email': 'fanchengyan2020@126.com'}\n",
">>> succeed post: {'N': 39.16527884776772, 'W': 98.34602960014247, 'S': 38.52041942953548, 'E': 99.41788862899489, 'H': 23, 'M': 26, 'date': '20170411\\n20170423\\n20170505\\n20170517\\n20170529\\n20170610\\n20170622\\n20170704\\n20170716\\n20170728\\n20170809\\n20170821\\n20170902\\n20170914\\n20171008\\n20171020\\n20171101', 'type': '2', 'email': 'fanchengyan2020@126.com'}\n",
">>> succeed post: {'N': 39.16527884776772, 'W': 98.34602960014247, 'S': 38.52041942953548, 'E': 99.41788862899489, 'H': 23, 'M': 26, 'date': '20171113\\n20171125\\n20171207\\n20171219\\n20171231\\n20180112\\n20180124\\n20180205\\n20180217\\n20180301\\n20180313\\n20180325\\n20180406\\n20180418\\n20180430\\n20180512\\n20180524', 'type': '2', 'email': 'fanchengyan2020@126.com'}\n",
">>> succeed post: {'N': 39.16527884776772, 'W': 98.34602960014247, 'S': 38.52041942953548, 'E': 99.41788862899489, 'H': 23, 'M': 26, 'date': '20180605\\n20180617\\n20180629\\n20180711\\n20180723\\n20180804\\n20180816\\n20180921\\n20181003\\n20181015\\n20181027\\n20181108\\n20181120\\n20181202\\n20181214\\n20181226\\n20190107', 'type': '2', 'email': 'fanchengyan2020@126.com'}\n",
">>> succeed post: {'N': 39.16527884776772, 'W': 98.34602960014247, 'S': 38.52041942953548, 'E': 99.41788862899489, 'H': 23, 'M': 26, 'date': '20190119\\n20190131\\n20190212\\n20190224\\n20190308\\n20190320\\n20190401\\n20190413\\n20190425\\n20190507\\n20190519\\n20190531\\n20190612\\n20190624\\n20190706\\n20190718\\n20190730', 'type': '2', 'email': 'fanchengyan2020@126.com'}\n",
">>> succeed post: {'N': 39.16527884776772, 'W': 98.34602960014247, 'S': 38.52041942953548, 'E': 99.41788862899489, 'H': 23, 'M': 26, 'date': '20190811\\n20190823\\n20190904\\n20191221\\n20200102\\n20200114\\n20200126\\n20200207\\n20200219\\n20200302\\n20200314\\n20200326\\n20200407\\n20200419\\n20200501\\n20200513', 'type': '2', 'email': 'fanchengyan2020@126.com'}\n",
" sleeping for 288 seconds...\n"
]
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "4aa82286c5414723adcddcc8d864c133",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
" 0%| | 0/5 [00:00<?, ?it/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
">>> succeed post: {'N': 39.16527884776772, 'W': 98.34602960014247, 'S': 38.52041942953548, 'E': 99.41788862899489, 'H': 23, 'M': 27, 'date': '20190916\\n20190928\\n20191010\\n20191022\\n20191103\\n20191115\\n20191127\\n20191209\\n20200525\\n20200606\\n20200618\\n20200630\\n20200712\\n20200724\\n20200805\\n20200817\\n20200829\\n20200910\\n20200922\\n20201004', 'type': '2', 'email': 'fanchengyan2020@126.com'}\n",
">>> succeed post: {'N': 39.16527884776772, 'W': 98.34602960014247, 'S': 38.52041942953548, 'E': 99.41788862899489, 'H': 23, 'M': 27, 'date': '20201016\\n20201028\\n20201109\\n20201121\\n20201203\\n20201215\\n20201227\\n20210108\\n20210120\\n20210201\\n20210213\\n20210225\\n20210309\\n20210321\\n20210402\\n20210414\\n20210426\\n20210508\\n20210520\\n20210601', 'type': '2', 'email': 'fanchengyan2020@126.com'}\n",
">>> succeed post: {'N': 39.16527884776772, 'W': 98.34602960014247, 'S': 38.52041942953548, 'E': 99.41788862899489, 'H': 23, 'M': 27, 'date': '20210613\\n20210625\\n20210707\\n20210719\\n20210731\\n20210812\\n20210824\\n20210905\\n20210917\\n20210929\\n20211011\\n20211023\\n20211104\\n20211116\\n20211128\\n20211210\\n20211222\\n20220103\\n20220115', 'type': '2', 'email': 'fanchengyan2020@126.com'}\n",
">>> succeed post: {'N': 39.16527884776772, 'W': 98.34602960014247, 'S': 38.52041942953548, 'E': 99.41788862899489, 'H': 23, 'M': 27, 'date': '20220127\\n20220208\\n20220220\\n20220304\\n20220316\\n20220328\\n20220409\\n20220421\\n20220503\\n20220515\\n20220527\\n20220620\\n20220702\\n20220714\\n20220726\\n20220807\\n20220819\\n20220831\\n20220912', 'type': '2', 'email': 'fanchengyan2020@126.com'}\n",
">>> succeed post: {'N': 39.16527884776772, 'W': 98.34602960014247, 'S': 38.52041942953548, 'E': 99.41788862899489, 'H': 23, 'M': 27, 'date': '20220924\\n20221006\\n20221018\\n20221030\\n20221111\\n20221123\\n20221205\\n20221217\\n20221229\\n20230110\\n20230122\\n20230203\\n20230215\\n20230227\\n20230311\\n20230323\\n20230404\\n20230814\\n20230907', 'type': '2', 'email': 'fanchengyan2020@126.com'}\n",
" sleeping for 743 seconds...\n"
]
}
],
"source": [
"# initialize a submitter with the dataset and your email\n",
"submitter = gacos.Submitter(ds, email=\"your_email@xxx.com\")\n",
"\n",
"# submit all gacos requests for acquisitions in the Hyp3 dataset\n",
"submitter.post_requests()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# check the status of all requests\n",
"print(f\"Successfully submitted requests: \\n{submitter.succeed}\")\n",
"print(f\"Failed to submit requests: \\n{submitter.failed}\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Retrieve GACOS results urls from your email automatically"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "667dccc73a434102a87226ebcb453389",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"Retrieving GACOS urls: 0%| | 0/240 [00:00<?, ? emails/s]"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"output_file = \"/Volumes/Data/Hyp3/descending_gacos/gacos_urls.csv\"\n",
"\n",
"email = gacos.GACOSEmail(\n",
" username=\"your_email\",\n",
" password=\"password_of_your_email\",\n",
" host=\"imap.xxx.com\", # imap server of your email\n",
" start_date=\"2023-11-01\", # only download gacos results for the email after this date\n",
")\n",
"email.retrieve_gacos_urls(output_file)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Download GACOS results using the urls "
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "b99066adfc1c4f24aa2164540cd03ce7",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
" 0%| | 0/24 [00:00<?, ?it/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "ed443926d42e480ca0d5d835ee23b377",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"20231116T010337VzTsCTN1h.tar.gz: 0%| | 0.00/15.6M [00:00<?, ?B/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "a40ea2c7a8da49eebc8dcb46d6e528ae",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"20231116T011307V7OXOyZBe.tar.gz: 0%| | 0.00/43.7M [00:00<?, ?B/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "478bae1d3f9545e7936e0436e21f48f3",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"20231116T011337VC4LikOAs.tar.gz: 0%| | 0.00/43.7M [00:00<?, ?B/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "35e60690588147028abbc997e1b0fdf6",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"20231116T011408V6h3BniJT.tar.gz: 0%| | 0.00/41.1M [00:00<?, ?B/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "b5797b66e4044865acac24bb6bdbe4bc",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"20231116T011237Vy7m1l2al.tar.gz: 0%| | 0.00/43.7M [00:00<?, ?B/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "ab235b358f7d477c9a8f367b1c969e04",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"20231116T011738Vniy7uNPV.tar.gz: 0%| | 0.00/51.2M [00:00<?, ?B/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "edd581a5a24049cfa884c7d47ff5fd6c",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"20231116T011808VcEaTHazf.tar.gz: 0%| | 0.00/48.8M [00:00<?, ?B/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "f4501c922a984f8e890e2196c8717742",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"20231116T011838VJaHXOaZJ.tar.gz: 0%| | 0.00/48.8M [00:00<?, ?B/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "025da6a325394f6195555963ebc48f30",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"20231116T142253VdcxwhZjh.tar.gz: 0%| | 0.00/15.6M [00:00<?, ?B/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "1e10f5c2420047dd9a20476e990be884",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"20231116T142324VXIAESwIW.tar.gz: 0%| | 0.00/43.7M [00:00<?, ?B/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "7f048fd91a7246f1adaa81de3c33a6f8",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"20231116T142354VQj8kS9I0.tar.gz: 0%| | 0.00/43.6M [00:00<?, ?B/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "b819434541c540898948615a24650eab",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"20231116T142424VMFCCq5W7.tar.gz: 0%| | 0.00/43.7M [00:00<?, ?B/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "9b2abbf34daf4b12b44a44dc6b902ed2",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"20231116T144425VSlcfYAm2.tar.gz: 0%| | 0.00/15.6M [00:00<?, ?B/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "89261f821810404281862ba336f56eb6",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"20231116T144455VCncFDojU.tar.gz: 0%| | 0.00/43.7M [00:00<?, ?B/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "d55f37d845454a0d90254ab82686b5d0",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"20231116T144525VisGJO2bU.tar.gz: 0%| | 0.00/43.7M [00:00<?, ?B/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "75bd725bd9bf43b0bfe03682db91c6a2",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"20231116T144555VcE1J5wo4.tar.gz: 0%| | 0.00/43.7M [00:00<?, ?B/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "53773e7ba770412da3b45fb63d014a98",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"20231116T145756VCHtI731i.tar.gz: 0%| | 0.00/15.6M [00:00<?, ?B/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "b7848836c32244759118c616b458a3c4",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"20231116T145827VhbjZbz5b.tar.gz: 0%| | 0.00/43.7M [00:00<?, ?B/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "f4f396e98e134ea08c8b6f5f9aa6138f",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"20231116T145857VUeNu4WnY.tar.gz: 0%| | 0.00/43.6M [00:00<?, ?B/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "7ef6ff94335c4db38c7f4d20a07d9f29",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"20231116T145927V2I8j7eo6.tar.gz: 0%| | 0.00/43.7M [00:00<?, ?B/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "1979604e57d3473b9ea7af1cd2e112bb",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"20231116T151057VQMukfvJ5.tar.gz: 0%| | 0.00/15.6M [00:00<?, ?B/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "7fcd89254e0e4335a20440b2cff80bcc",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"20231116T151158Vx3KrT8Va.tar.gz: 0%| | 0.00/43.7M [00:00<?, ?B/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "7550835c8d834f8895efea89ede2d308",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"20231116T151228VcpWSrjqg.tar.gz: 0%| | 0.00/43.7M [00:00<?, ?B/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"data": {
"application/vnd.jupyter.widget-view+json": {
"model_id": "d42edcb7dfd546aca10f4cd4635e3cc1",
"version_major": 2,
"version_minor": 0
},
"text/plain": [
"20231116T151258VfhhwgAli.tar.gz: 0%| | 0.00/43.7M [00:00<?, ?B/s]"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"url_file = output_file\n",
"output_dir = \"/Volumes/Data/Hyp3/descending_gacos\"\n",
"\n",
"gacos_dl = gacos.Downloader(url_file, output_dir, time=23.43)\n",
"gacos_dl.download()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "geo",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.6"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
@@ -0,0 +1,4 @@
from .datasets import LiCSARDataset, SarDataset, HyP3Dataset
from .parse_email import GACOSEmail
from .submit import Submitter
from .download import Downloader
@@ -0,0 +1,276 @@
import warnings
from pathlib import Path
from typing import Literal, Optional, Union
import numpy as np
import pandas as pd
try:
from faninsar.datasets import HyP3, LiCSAR
except ImportError:
try:
from faninsar.datasets import hyp3 as HyP3, licsar as LiCSAR
except ImportError:
HyP3 = None
LiCSAR = None
warnings.filterwarnings("ignore")
class SarDataset:
def __init__(
self,
bounds: tuple[float, float, float, float],
date_times: pd.DatetimeIndex,
gacos_dir: Optional[Union[Path, str]] = None,
) -> None:
"""Initialize SarDataset class
Parameters
----------
bounds : tuple[float, float, float, float]
The bounding box of the dataset.
date_times : pd.DatetimeIndex
The datetime index of the dataset.
gacos_dir : Optional[Union[Path, str]], optional
The directory used to save gacos data. Used to check if the data is
already downloaded and avoid resubmitting. Default is None.
"""
self.bounds = bounds
self._date_times = date_times
self._dates = date_times.strftime("%Y%m%d")
if gacos_dir is not None:
self._dates_remain = self._get_dates_remain(gacos_dir)
else:
self._dates_remain = self.dates
hour = date_times.hour
minute = np.round((date_times.second / 60) + date_times.minute).astype(int)
times = pd.Series([f"{h:02d}:{m:02d}" for h, m in zip(hour, minute)])
self._times = times
self._times_remain = self._get_times_remain()
def __str__(self) -> str:
return (
f"{self.__class__.__name__}(\n"
f" bounds={self.bounds}, \n"
f" times={len(self.times)}, \n"
f" dates={len(self.dates)}\n"
")"
)
def __repr__(self) -> str:
return self.__str__()
def _get_dates_remain(self, gacos_dir: Union[Path, str]):
"""Get the dates that are not downloaded yet.
Parameters
----------
gacos_dir : Union[Path, str]
The directory used to save gacos data. Used to check if the data is
already downloaded and avoid resubmitting.
Returns
-------
dates_remain : np.ndarray
The dates that are not downloaded yet.
"""
gacos_files = list(Path(gacos_dir).rglob("*.ztd.tif"))
gacos_dates = []
for i in gacos_files:
stem = i.stem.split(".")[0]
if len(stem) == 8:
gacos_dates.append(stem)
dates_remain = np.setdiff1d(self.dates, gacos_dates)
return dates_remain
def _get_times_remain(self):
"""Get the times corresponding to the dates that are not downloaded yet."""
idx = np.where(np.isin(self.dates, self.dates_remain))[0]
times_remain = self._times[idx]
return times_remain
@property
def dates(self):
"""The dates (YYYYMMDD) of the acquisitions parsed from dataset."""
return self._dates
@property
def times(self):
"""The times (HH:MM) of the acquisitions parsed from dataset."""
return self._times.unique()
@property
def date_times(self):
"""The datetime of the acquisitions parsed from dataset."""
return self._date_times
@property
def dates_remain(self):
"""The dates that are not downloaded yet. If gacos_dir is None, then
dates_remain is the same as dates."""
return self._dates_remain
@property
def times_remain(self):
"""The times corresponding to the dates that are not downloaded yet."""
return self._times_remain
def gen_datetime_patches(
self,
mode: Literal["all", "remain"] = "remain",
) -> dict:
"""Generate datetime patches.
Parameters
----------
mode : Literal["all", "remain"], optional
The mode to generate datetime patches. If "all", then generate all
the datetime patches. If "remain", then generate the datetime
patches of the dates that are not downloaded yet. Default is
"remain".
Returns
-------
datetime_patches : dict
The datetime patches. The key is the time (HH:MM) and the value is
the datetime patches.
"""
nums = 20
datetime_patches = {}
if mode == "all":
for _time in self.times:
_dts = self.dates[self._times == _time]
n_patch = np.ceil(len(_dts) / nums)
dates_patch = np.array_split(_dts, n_patch)
datetime_patches[_time] = dates_patch
elif mode == "remain":
for _time in self.times_remain:
_dts = self.dates_remain[self._times_remain == _time]
n_patch = np.ceil(len(_dts) / nums)
dates_patch = np.array_split(_dts, n_patch)
datetime_patches[_time] = dates_patch
return datetime_patches
def gen_post_data(
self,
dates: Union[list, np.ndarray],
times: Union[tuple[int, int], tuple[str, str]],
email: str,
):
"""Generate post data for gacos website.
Parameters
----------
dates : list or np.ndarray
The list of dates.
times : tuple[int, int]
The time of the acquisition (hour, minute).
email : str
The email address to receive the gacos data.
Returns
-------
post_data : dict
The post data.
"""
if isinstance(dates, np.ndarray):
dates = dates.tolist()
times = [int(t) for t in times]
post_data = {
"N": self.bounds[3],
"W": self.bounds[0],
"S": self.bounds[1],
"E": self.bounds[2],
"H": times[0],
"M": times[1],
"date": "\n".join(dates),
"type": "2",
"email": email,
}
return post_data
class LiCSARDataset(SarDataset):
def __init__(
self,
home_dir: Union[Path, str],
gacos_dir: Optional[Union[Path, str]] = None,
) -> None:
"""Initialize LiCSARDataset class
Parameters
----------
home_dir : Union[Path, str]
The home directory of LiCSAR dataset.
gacos_dir : Optional[Union[Path, str]], optional
The directory used to save gacos data. Used to check if the data is
already downloaded and avoid resubmitting. Default is None.
"""
self.home_dir = Path(home_dir)
self.dataset = LiCSAR(home_dir)
bounds = self.dataset.bounds
time = self._get_time()
dates = self.dataset.pairs.dates
date_times = pd.to_datetime([f"{d} {time[0]}:{time[1]}:00" for d in dates])
super().__init__(bounds, date_times, gacos_dir)
def _get_time(self):
"""Get the acquisition time of acquisitions.
Returns
-------
time: tuple[int, int]
A tuple of hour and minute representing the acquisition time.
Raises
------
ValueError
If no center_time found in metadata.txt.
"""
meta_file = sorted(self.home_dir.rglob("metadata.txt"))[0]
with open(meta_file) as f:
lines = f.readlines()
time = None
for line in lines:
line_split = line.split("=")
key, value = (line_split[0].strip(), line_split[1])
if "center_time" == key:
center_time = value.strip()
hour, minute, second = center_time.split(":")
hour, minute, second = int(hour), int(minute), float(second)
minute = minute + int(np.round(second / 60, 0))
return hour, minute
else:
continue
if time is None:
raise ValueError(f"No center_time found in {meta_file}")
class HyP3Dataset(SarDataset):
def __init__(
self,
home_dir: Union[Path, str],
gacos_dir: Optional[Union[Path, str]] = None,
) -> None:
"""Initialize HyP3Dataset class
Parameters
----------
home_dir : Union[Path, str]
The home directory of HyP3 dataset.
gacos_dir : Optional[Union[Path, str]], optional
The directory used to save gacos data. Used to check if the data is
already downloaded and avoid resubmitting. Default is None.
"""
self.dataset = HyP3(home_dir)
bounds = self.dataset.bounds.to_crs("epsg:4326")
date_times = self.dataset.datetime
super().__init__(bounds, date_times, gacos_dir)
@@ -0,0 +1,158 @@
import tarfile
from pathlib import Path
from typing import Optional, Union
import numpy as np
import pandas as pd
from data_downloader import downloader
from faninsar.query import BoundingBox
from tqdm.auto import tqdm
from .parse_email import GACOSEmail
class Downloader:
def __init__(
self,
url_file: Union[Path, str],
output_dir: Union[Path, str],
tar_gz_dir: Optional[Union[Path, str]] = None,
keep_original: bool = False,
times: Optional[Union[float, list[float]]] = None,
bounds: Optional[tuple[float, float, float, float]] = None,
) -> None:
"""Initialize Downloader class
Parameters
----------
url_file : Union[Path, str]
Path to file containing URLs that created by :meth:`GACOSEmail.retrieve_gacos_urls`
output_dir : Union[Path, str]
directory to output gacos files
tar_gz_dir : Optional[Union[Path, str]], optional
directory to store downloaded *.tar.gz files. If None, then
`output_dir` is used. Default is None.
keep_original : bool, optional
Whether to keep original files (*.tar.gz). Default is False.
times : Optional[float], optional
times of acquisition, used to filter out files that are not needed.
this can be a single time or a list of times. times differ by less
than 10 minutes are considered the same. Default is None.
bounds : Optional[tuple[float, float, float, float]], optional
bounds of area of interest with order (W, S, E, N), used to filter
out files that are not needed. Default is None.
"""
self.url_file = Path(url_file)
self.output_dir = Path(output_dir)
if tar_gz_dir is None:
self.tar_gz_dir = self.output_dir
self.keep_original = keep_original
if not self.url_file.exists():
raise FileNotFoundError(f"{self.url_file} does not exist")
if not self.output_dir.exists():
self.output_dir.mkdir(parents=True)
if not self.tar_gz_dir.exists():
self.tar_gz_dir.mkdir(parents=True)
self.df_urls = pd.read_csv(self.url_file, header=0)
# only keep urls that intersect with bounds
if bounds is not None:
mask_bbox = self._bbox_mask(BoundingBox(*bounds))
# only keep urls that acquisition time is within 10 minutes of `time`
if times is not None:
if isinstance(times, float):
times = [times]
mask_time = self._time_mask(times)
if bounds is not None and times is not None:
self.mask = mask_bbox & mask_time
elif bounds is not None:
self.mask = mask_bbox
elif times is not None:
self.mask = mask_time
else:
self.mask = np.ones(self.df_urls.shape[0], dtype=bool)
self.mask = self.mask & self.date_mask
def _bbox_mask(self, bounds) -> np.ndarray:
intersection_bbox = np.array(
[
BoundingBox(*b).intersects(bounds)
for b in zip(
self.df_urls["south"].astype(float),
self.df_urls["west"].astype(float),
self.df_urls["north"].astype(float),
self.df_urls["east"].astype(float),
)
]
)
return intersection_bbox
def _time_mask(self, times) -> np.ndarray:
"""Only keep urls that acquisition time is within 10 minutes of `time`"""
intersection_times = []
for time in times:
intersection_times.append(
np.array(
np.abs(self.df_urls["time"].astype(float) - time)
<= 1 / 60 * 10 # 10 minutes
)
)
intersection_time = np.any(intersection_times, axis=0)
return intersection_time
@property
def date_mask(self) -> np.ndarray:
"""Remove urls that all acquisition dates have been downloaded"""
dates_urls = self.df_urls["date"].map(lambda x: eval(x))
intersection_dates = []
for dt_url in dates_urls:
intersection_dates.append(~np.all(np.isin(dt_url, self.dates_downloaded)))
return np.array(intersection_dates)
@property
def dates_downloaded(self) -> np.ndarray:
"""Return dates that have been downloaded"""
gacos_files = list(self.output_dir.rglob("*.ztd.tif"))
dates = []
for i in gacos_files:
stem = i.stem.split(".")[0]
if len(stem) == 8:
dates.append(stem)
return np.array(dates)
def download(self) -> None:
"""Download GACOS files from URLs in file created by :meth:`GACOSEmail.retrieve_gacos_urls`"""
urls_used = self.df_urls[self.mask]["url"].values
for url in tqdm(urls_used, unit="file", desc="Downloading GACOS files"):
gz_file = self.tar_gz_dir / Path(url).name
downloader.download_data(url, file_name=gz_file)
self._extract_tar_gz(gz_file)
if not self.keep_original:
self._delete_file(gz_file)
def _extract_tar_gz(self, gz_file) -> None:
"""Unzip/extract downloaded GACOS files
Parameters
----------
gz_file : Path
path to downloaded GACOS file (*.tar.gz)
"""
with tarfile.open(gz_file, "r:gz") as tar:
tar.extractall(path=self.output_dir)
def _delete_file(self, gz_file) -> None:
"""Delete original GACOS files
Parameters
----------
gz_file : Path
path to downloaded GACOS file (*.tar.gz)
"""
gz_file.unlink()
@@ -0,0 +1,391 @@
import email
import email.message
import getpass
import imaplib
import poplib
import re
from email.parser import Parser
from email.utils import parseaddr
from pathlib import Path
from typing import Literal, Optional, Union
import pandas as pd
from tqdm.auto import tqdm
class GACOSEmail:
"""a class to retrieve gacos urls from email.
.. note::
The IMAP server is used to retrieve content from email. Some email
service providers may need to enable the IMAP service in the settings.
**You are recommended to use a new email account to receive gacos urls to
avoid polluting your own email account**.
"""
def __init__(
self,
username: str,
password: str,
host: str,
prompt: bool = False,
email_protocol: Literal["imap", "pop3"] = "imap",
port: Optional[int] = None,
gacos_email: str = "gacos2017@foxmail.com",
gacos_suffix: str = "tar.gz",
start_date: Optional[str] = None,
end_date: Optional[str] = None,
date_args: Optional[dict] = None,
ssl: bool = False,
) -> None:
"""Retrieve gacos urls from email.
Parameters
----------
username : str
The username of the email address.
password : str
The password.
host : str
The host of the email address. For example, the host of gmail for
imap is "imap.gmail.com". You can find the host of your email
settings or search it on the Internet.
prompt: bool, optional
Prompt for username and/or password interactively when they are not
provided as keyword parameters. Default is False.
email_protocol : str, one of ["imap", "pop3"], optional
The protocol of the email. Default is "imap".
port : int, optional
The port of the host of your email. If None, the default port will be
used. Default is None.
gacos_email : str, optional
The email address of gacos. Default is "gacos2017@foxmail.com".
gacos_suffix : str, optional
The suffix of the gacos file url. Default is "tar.gz". The suffix is used
to filter urls in the email. This parameter is used to avoid the
situation that the email contains other urls.
start_date / end_date: str, optional
The start/end date of email. Used to filter the email. Default is None. Can be any format that can be parsed by pandas.to_datetime.
date_args : dict, optional
The arguments are passed to pandas.to_datetime. Default is None.
ssl : bool, optional
Whether to use SSL connection. Default is False.
"""
if prompt:
self.username = None
self.password = None
else:
self.username = username
self.password = password
self.host = host
self.email_protocol = email_protocol
self.port = port
self.gacos_email = gacos_email
self.gacos_suffix = gacos_suffix
self.ssl = ssl
# date part
self.start_date = start_date
self.end_date = end_date
if date_args is None:
date_args = {}
self.date_args = date_args
def _retrieve_gacos_urls_pop3(self):
server = login_in_email_pop3(
self.username, self.password, self.host, self.port, ssl=self.ssl
)
print(server.getwelcome())
nums = server.stat()[0]
gacos = []
for i in tqdm(range(1, nums + 1), unit=" emails", desc="Retrieving GACOS Urls"):
response, msgLines, octets = server.retr(i)
msgLinesToStr = b"\r\n".join(msgLines).decode("utf8", "ignore")
messageObject = Parser().parsestr(msgLinesToStr)
senderContent = messageObject["From"]
senderRealName, senderAdr = parseaddr(senderContent)
if senderAdr == self.gacos_email:
if not in_date_range(
pd.to_datetime(messageObject["Date"]).tz_localize(None),
self.start_date,
self.end_date,
self.date_args,
):
continue
msgBodyContents = get_content(messageObject)
info = parse_gacos_info(
msgBodyContents,
gacos_suffix=self.gacos_suffix,
)
if info is not None:
gacos.append(info)
server.quit()
return gacos
def _retrieve_gacos_urls_imap(self):
server = login_in_email_imap(
self.username, self.password, self.host, self.port, ssl=self.ssl
)
if server is None:
print("IMAP server connection failed, skipping email check.")
return []
server.select("inbox")
status, data = server.search(None, "ALL")
gacos = []
for i in tqdm(data[0].split(), unit=" emails", desc="Retrieving GACOS urls"):
res, msg = server.fetch(i, "(RFC822)")
for response_part in msg:
if isinstance(response_part, tuple):
msgLines = response_part[1].decode("utf8", "ignore")
break
messageObject = Parser().parsestr(msgLines)
senderContent = messageObject["From"]
senderRealName, senderAdr = parseaddr(senderContent)
if senderAdr == self.gacos_email:
if not in_date_range(
pd.to_datetime(messageObject["Date"]).tz_localize(None),
self.start_date,
self.end_date,
self.date_args,
):
continue
msgBodyContents = get_content(messageObject)
info = parse_gacos_info(
msgBodyContents,
gacos_suffix=self.gacos_suffix,
)
if info is not None:
gacos.append(info)
server.close()
return gacos
def retrieve_gacos_urls(
self,
output_file: Union[str, Path],
):
"""Retrieve gacos urls from username.
Parameters
----------
output_file : str or Path
The output file used to save the gacos urls.
"""
if self.email_protocol == "pop3":
gacos = self._retrieve_gacos_urls_pop3()
elif self.email_protocol == "imap":
gacos = self._retrieve_gacos_urls_imap()
else:
raise ValueError("email_protocol must be 'pop3' or 'imap'.")
cols = ["url", "south", "north", "west", "east", "time", "date"]
df_gacos = pd.DataFrame(gacos, columns=cols).drop_duplicates(subset="url")
# save to file
try:
df_gacos.to_csv(output_file)
print(f"Save gacos urls to {output_file}")
except Exception as e:
self.df_gacos = df_gacos
print(e)
print("Save gacos urls failed")
print("You can access the gacos urls by `df_gacos` attribute.")
def in_date_range(date, start_date, end_date, date_args={}):
start_date = pd.to_datetime(start_date, **date_args)
end_date = pd.to_datetime(end_date, **date_args)
start_none = start_date is None or pd.isna(start_date)
end_none = end_date is None or pd.isna(end_date)
if start_none and end_none:
return True
elif start_none:
return date <= end_date
elif end_none:
return date >= start_date
else:
return (date >= start_date) and (date <= end_date)
def decodeBody(msgPart: email.message.Message):
"""decode email body
Parameters
----------
msgPart : email.message.Message
The email message object.
"""
contentType = msgPart.get_content_type()
textContent = ""
if contentType == "text/plain" or contentType == "text/html":
content = msgPart.get_payload(decode=True)
charset = msgPart.get_charset()
if charset is None:
contentType = msgPart.get("Content-Type", "").lower()
position = contentType.find("charset=")
if position >= 0:
charset = contentType[position + 8 :].strip()
if charset:
textContent = content.decode(charset)
return textContent
def get_content(messageObject):
msgBodyContents = []
if messageObject.is_multipart(): # parse multipart email
messageParts = messageObject.get_payload()
for messagePart in messageParts:
bodyContent = decodeBody(messagePart)
if bodyContent:
msgBodyContents.append(bodyContent)
else:
bodyContent = decodeBody(messageObject)
if bodyContent:
msgBodyContents.append(bodyContent)
return msgBodyContents
def login_in_email_pop3(username, password, host, port, ssl=False):
try:
if username is None:
username = input("username: ")
if password is None:
password = getpass.getpass("password: ")
if ssl:
if port is None:
port = 995
server = poplib.POP3_SSL(host, port)
else:
if port is None:
port = 110
server = poplib.POP3(host, port)
server.user(username)
server.pass_(password)
return server
except Exception as e:
print(e)
print("login failed")
def login_in_email_imap(username, password, host, port, ssl=False):
try:
if username is None:
username = input("username: ")
if password is None:
password = getpass.getpass("password: ")
if ssl:
if port is None:
port = 993
else:
if port is None:
port = 143
# 强制 IPv4: monkey-patch getaddrinfo,避免 IPv6 不可达
import socket as _socket
_orig_getaddrinfo = _socket.getaddrinfo
def _ipv4_only_getaddrinfo(*args, **kwargs):
return _orig_getaddrinfo(args[0], args[1], _socket.AF_INET,
*args[3:], **kwargs)
_socket.getaddrinfo = _ipv4_only_getaddrinfo
try:
if ssl:
server = imaplib.IMAP4_SSL(host, port)
else:
server = imaplib.IMAP4(host, port)
finally:
_socket.getaddrinfo = _orig_getaddrinfo
server.login(username, password)
# 163/126 等网易邮箱要求登录后发送 ID 命令才能执行 SELECT
if '163.com' in host or '126.com' in host or 'yeah.net' in host:
try:
tag = server._new_tag()
server.send(tag + b' ID ("name" "pyint" "version" "1.0" '
b'"vendor" "pyint")\r\n')
while True:
resp = server.readline()
if resp.startswith(tag):
break
except Exception:
pass
return server
except Exception as e:
print(f"IMAP login failed: {e}")
return None
def parse_gacos_info(msgBodyContents, gacos_suffix="tar.gz"):
"""Parse gacos info from email body.
Parameters
----------
msgBodyContents : list
The email body contents.
gacos_suffix : str, optional
The suffix of the gacos file url. Default is "tar.gz". The suffix is used
to filter urls in the email. This parameter is used to avoid the
situation that the email contains other urls.
"""
url, south, north, west, east, _time, date_list = (
None,
None,
None,
None,
None,
None,
None,
)
date_list = []
for contents in msgBodyContents:
lines = [i.strip() for i in contents.split("\n") if i]
for line in lines:
line = line.strip()
loc = line.split("=")
if len(loc) == 2:
parameter, value = loc
parameter, value = (parameter.strip(), value.strip())
if "MinLat" == parameter:
south = float(value)
if "MaxLat" == parameter:
north = float(value)
if "MinLon" == parameter:
west = float(value)
if "MaxLon" == parameter:
east = float(value)
loc = line.split(":")
if len(loc) == 2:
parameter, value = loc
parameter, value = (parameter.strip(), value.strip())
if "Time" == parameter:
_time = float(value)
if len(line) == 8 and line.isdigit():
date_list.append(line)
for i in ["http", "ftp", "https"]:
result = re.search(f"\({i}.*{gacos_suffix}\)", line)
if result:
url = result.group()[1:-1]
break
if url == south == north == west == east == _time:
return None
else:
return url, south, north, west, east, _time, date_list
@@ -0,0 +1,83 @@
import time
from pathlib import Path
from typing import Optional, Union
import numpy as np
import requests
from tqdm.auto import tqdm
from .datasets import SarDataset
class Submitter:
def __init__(
self,
dataset: SarDataset,
email: str,
sleep_time_range: tuple[int, int] = (60 / 2, 60 * 5),
gacos_url="http://www.gacos.net/M/action_page.php",
) -> None:
"""Initialize Submitter class
Parameters
----------
dataset : SarDataset
The SarDataset object.
email : str
The email address to submit to gacos.
sleep_time_range : tuple[int, int], optional
The range of sleep time in seconds. Default is (60, 60 * 5).
gacos_url : str, optional
The url of gacos website. Default is "http://www.gacos.net/M/action_page.php".
"""
self.dataset = dataset
self.email = email
self.sleep_time_range = sleep_time_range
self.gacos_url = gacos_url
self._failed = []
self._succeed = []
def _post_data(self, data):
"""Post data to gacos website."""
r = requests.post(self.gacos_url, data=data)
return "Thanks for using GACOS!" in r.text
def post_requests(self):
# post gacos info to website
datetime_patches = self.dataset.gen_datetime_patches()
for _key, _dates in tqdm(
datetime_patches.items(),
desc="submitting times",
unit="times",
):
try:
for _dt in tqdm(_dates, desc="submitting dates", unit="dates"):
post_data = self.dataset.gen_post_data(
_dt, _key.split(":"), self.email
)
status_ok = self._post_data(post_data)
if status_ok:
self._succeed.append(post_data)
tqdm.write(f">>> succeed post: {post_data}")
else:
self._failed.append(post_data)
tqdm.write(f">>> failed post: {post_data}")
# wait to avoid be rejected
sleep_time = np.random.randint(*self.sleep_time_range)
tqdm.write(f" sleeping for {sleep_time} seconds...")
time.sleep(sleep_time)
except:
self._failed.append(post_data)
tqdm.write(f">>> failed post: {post_data}")
@property
def failed(self):
"""A list of failed post data."""
return self._failed
@property
def succeed(self):
"""A list of succeed post data."""
return self._succeed
@@ -0,0 +1,23 @@
[project]
name = "AutoGACOS"
authors = [{name = "Fancy", email = "fanchengyan@outlook.com"}]
description = "A Python library for automatically submitting and downloading GACOS data"
version = "0.1.0"
requires-python = ">=3.6"
dependencies = [
"data_downloader",
"faninsar",
]
readme = "README.md"
license = {file = "LICENSE"}
keywords = ["GACOS", "data", "downloader"]
[project.optional-dependencies]
dev = [
"pytest"
]
[project.urls]
Homepage = "https://github.com/Fanchengyan/AutoGACOS"
Repository = "https://github.com/Fanchengyan/AutoGACOS"
@@ -0,0 +1,265 @@
# DEM 数据下载指南
本文档介绍如何使用 `makedem.py` 下载和处理不同来源的 DEM 数据。
## 支持的 DEM 数据源
### 1. Copernicus DEM (默认推荐)
**特点:**
- 分辨率: 30米
- 覆盖: 全球 (60°S - 80°N)
- 数据质量: 高精度,全球一致性
- 下载方式: 自动从 AWS/OpenTopography 下载
- 费用: 免费
**使用方法:**
```bash
# 基本使用
python makedem.py -r 116/117/39/40 --dem-source copernicus
# 指定并行下载数量(加速下载)
python makedem.py -r 116/117/39/40 --dem-source copernicus --num-workers 8
# 指定输出目录
python makedem.py -r 116/117/39/40 --dem-source copernicus --dir /path/to/output
```
**优点:**
- ✓ 全自动下载
- ✓ 高精度数据
- ✓ 全球覆盖
- ✓ 支持并行下载加速
**缺点:**
- ✗ 需要网络连接
- ✗ 下载时间取决于网络速度
---
### 2. NASADEM
**特点:**
- 分辨率: 30米
- 覆盖: 全球 (60°S - 60°N)
- 数据质量: SRTM + ICESat 数据融合
- 下载方式: 通过 NASADEM Python 库自动下载
- 费用: 免费
**依赖安装:**
```bash
pip install nasadem rasters
```
**使用方法:**
```bash
# 基本使用
python makedem.py -r 116/117/39/40 --dem-source nasadem
# 指定输出目录
python makedem.py -r 116/117/39/40 --dem-source nasadem --dir /path/to/output
```
**优点:**
- ✓ 全自动下载
- ✓ NASA官方数据
- ✓ 融合多源数据,精度提升
**缺点:**
- ✗ 需要网络连接
- ✗ 首次下载可能较慢
- ✗ 需要额外安装库
- ✗ 覆盖范围小于 Copernicus (南北纬60°限制)
---
### 3. SRTM (需要预下载数据)
**特点:**
- 分辨率: 30米 (SRTM 1 arc-second) 或 90米 (SRTM 3 arc-second)
- 覆盖: 全球 (60°S - 60°N)
- 数据质量: 良好
- 下载方式: 需要手动预下载 .hgt 文件
- 费用: 免费
**依赖安装:**
```bash
# 注意: srtm库需要 Python >= 3.12
pip install srtm
# 检查Python版本
python --version # 应该显示 3.12 或更高版本
```
**Python版本要求:**
- srtm 库要求 Python >= 3.12
- 如果您的Python版本 < 3.12,建议使用 Copernicus 或 NASADEM
**数据准备步骤:**
1. **下载 SRTM .hgt 文件**
从以下网站之一下载所需区域的 .hgt 或 .hgt.zip 文件:
- **CSI-CGIAR SRTM**: https://srtm.csi.cgiar.org/ (推荐,无需注册)
- **USGS EarthExplorer**: https://earthexplorer.usgs.gov/ (需要注册)
- **NASA EarthData**: https://urs.earthdata.nasa.gov/ (需要注册)
2. **文件命名规则**
SRTM 文件按 1°×1° 分块命名:
- `N39E116.hgt` → 北纬39-40°, 东经116-117°
- `N39W110.hgt` → 北纬39-40°, 西经110-109°
- `S10E120.hgt` → 南纬10-9°, 东经120-121°
3. **数据组织**
将所有 .hgt 文件放在同一目录下,例如:
```
/path/to/srtm_data/
├── N39E116.hgt
├── N39E117.hgt
├── N40E116.hgt
└── N40E117.hgt
```
**使用方法:**
```bash
# 指定SRTM数据目录
python makedem.py -r 116/117/39/40 --dem-source srtm --srtm-data-dir /path/to/srtm_data
# 注意:如果不指定 --srtm-data-dir,程序会报错并提示
python makedem.py -r 116/117/39/40 --dem-source srtm
# 错误: 使用 SRTM 数据源需要指定 --srtm-data-dir 参数
```
**优点:**
- ✓ 离线使用(数据预下载后)
- ✓ 不依赖实时网络下载
- ✓ 数据源多样化
**缺点:**
- ✗ 需要手动下载数据文件
- ✗ 需要自行管理数据文件
- ✗ 需要确保覆盖目标区域的所有分块
- ✗ srtm 库对 .hgt.zip 压缩文件支持不稳定,建议解压后使用
---
## 使用建议
### 推荐使用顺序:
1. **首选: Copernicus DEM**
- 全自动,高精度,全球覆盖
- 使用 `--num-workers 8` 加速下载
2. **备选: NASADEM**
- 全自动,NASA官方数据
- 适合北纬60°以南,南纬60°以北区域
3. **离线环境: SRTM**
- 仅在无网络环境或已有SRTM数据时使用
- 需要提前准备数据文件
### 性能对比:
| DEM源 | 下载速度 | 数据精度 | 全球覆盖 | 离线使用 | 推荐指数 |
|-------|---------|---------|---------|---------|---------|
| Copernicus | ★★★★☆ | ★★★★★ | ★★★★★ | ✗ | ★★★★★ |
| NASADEM | ★★★☆☆ | ★★★★☆ | ★★★☆☆ | ✗ | ★★★★☆ |
| SRTM | N/A (离线) | ★★★★☆ | ★★★☆☆ | ✓ | ★★★☆☆ |
### 常见问题:
**Q: 如何确定需要下载哪些 SRTM 文件?**
A: 根据目标区域范围计算所需文件:
```python
# 示例: 区域 116/117/39/40 (东经116-117°, 北纬39-40°)
west, east, south, north = 116, 117, 39, 40
# 需要下载的文件:
# N39E116.hgt (39-40°N, 116-117°E)
# 如果区域更大,需要下载多个文件
```
**Q: SRTM .hgt.zip 文件可以直接使用吗?**
A: srtm 库对压缩文件支持不稳定,建议先解压:
```bash
cd /path/to/srtm_data/
unzip "*.hgt.zip"
```
**Q: 如何加速 Copernicus DEM 下载?**
A: 增加并行下载数量:
```bash
# 默认使用 4 个线程
python makedem.py -r 116/117/39/40 --dem-source copernicus --num-workers 4
# 加速到 8-16 个线程(根据网络情况调整)
python makedem.py -r 116/117/39/40 --dem-source copernicus --num-workers 16
```
**Q: 下载的数据格式是什么?**
A: 所有DEM源最终都会转换为 GAMMA/ROI_PAC 格式:
- `.dem` 文件: 二进制高程数据 (big-endian for GAMMA)
- `.dem.par` 文件: 参数文件
---
## 示例工作流程
### 场景1: 处理Sentinel-1数据(推荐Copernicus)
```bash
# 1. 确定研究区域范围
# 使用 SLC 参数文件自动确定
python makedem.py -s /path/to/slc.par --dem-source copernicus --num-workers 8
# 或手动指定区域
python makedem.py -r 116/117/39/40 --dem-source copernicus --num-workers 8
```
### 场景2: 离线处理(使用SRTM)
```bash
# 1. 提前下载SRTM数据
# 从 https://srtm.csi.cgiar.org/ 下载 N39E116.hgt, N39E117.hgt 等
# 2. 组织数据
mkdir -p ~/data/SRTM
mv N*.hgt ~/data/SRTM/
# 3. 使用预下载数据生成DEM
python makedem.py -r 116/117/39/40 --dem-source srtm --srtm-data-dir ~/data/SRTM
```
### 场景3: NASADEM对比测试
```bash
# 下载Copernicus DEM
python makedem.py -r 116/117/39/40 --dem-source copernicus --dir ./copernicus
# 下载NASADEM
python makedem.py -r 116/117/39/40 --dem-source nasadem --dir ./nasadem
# 对比两个DEM文件
# 使用 GMT 或其他工具进行可视化和分析
```
---
## 参考资料
- **Copernicus DEM**: https://copernicus-dem-90m.s3.amazonaws.com/readme.html
- **NASADEM**: https://github.com/DFS-iData/NASADEM
- **SRTM CSI-CGIAR**: https://srtm.csi.cgiar.org/
- **GAMMA Software**: https://gamma-rs.ch/
---
**最后更新**: 2026-03-13
**作者**: iFlow CLI
@@ -0,0 +1,193 @@
#! /usr/bin/env python
#'''
##################################################################################
# #
# Author: Yun-Meng Cao #
# Email : ymcmrs@gmail.com #
# Date : June, 2019 #
# #
# Generate SLC from SAR_IMS_P1 data #
# #
##################################################################################
#'''
import numpy as np
import os
import sys
import subprocess
import getopt
import time
import glob
from pyint import _utils as ut
def check_variable_name(path):
s=path.split("/")[0]
if len(s)>0 and s[0]=="$":
p0=os.getenv(s[1:])
path=path.replace(path.split("/")[0],p0)
return path
def read_template(File, delimiter='='):
'''Reads the template file into a python dictionary structure.
Input : string, full path to the template file
Output: dictionary, pysar template content
Example:
tmpl = read_template(KyushuT424F610_640AlosA.template)
tmpl = read_template(R1_54014_ST5_L0_F898.000.pi, ':')
'''
template_dict = {}
for line in open(File):
line = line.strip()
c = [i.strip() for i in line.split(delimiter, 1)] #split on the 1st occurrence of delimiter
if len(c) < 2 or line.startswith('%') or line.startswith('#'):
next #ignore commented lines or those without variables
else:
atrName = c[0]
atrValue = str.replace(c[1],'\n','').split("#")[0].strip()
atrValue = check_variable_name(atrValue)
template_dict[atrName] = atrValue
return template_dict
def UseGamma(inFile, task, keyword):
if task == "read":
f = open(inFile, "r")
while 1:
line = f.readline()
if not line: break
if line.count(keyword) == 1:
strtemp = line.split(":")
value = strtemp[1].strip()
return value
print("Keyword " + keyword + " doesn't exist in " + inFile)
f.close
def rm(TXT):
call_str = 'rm ' + TXT
os.system(call_str)
def usage():
print('''
******************************************************************************************************
Generate SLC and SLC_par file for ERS/ENVISAT (SAR_IMS_1P format)
usage:
Down2SLC_ERS.py ProjectName DownName
e.g. Down2SLC_ERS.py CotopaxiT120ERSA 910101
*******************************************************************************************************
''')
def main(argv):
if len(sys.argv)==3:
projectName = sys.argv[1]
Date = sys.argv[2]
else:
usage();sys.exit(1)
scratchDir = os.getenv('SCRATCHDIR')
templateDir = os.getenv('TEMPLATEDIR')
projectDir = scratchDir + '/' + projectName
downDir = scratchDir + '/' + projectName + "/DOWNLOAD"
slcDir = scratchDir + '/' + projectName + '/SLC'
workflow = downDir + '/' + Date
templateFile = templateDir + "/" + projectName + ".template"
templateDict=ut.update_template(templateFile)
rlks = templateDict['range_looks']
azlks = templateDict['azimuth_looks']
if not os.path.isdir(slcDir):
call_str= 'mkdir ' +slcDir
os.system(call_str)
os.chdir(workflow)
tempfile=workflow + '/' + 'workreport'
if os.path.isfile(tempfile):
tempDict=ut.update_template(tempfile)
CEOS_SAR_leader = tempDict['Pdi_L10ProductFileName02'].split('"')[1]
CEOS_raw_data = tempDict['Pdi_L10ProductFileName03'].split('"')[1]
Date0 = Date
# if len(Date)==6:
# Date0 = Date
# elif len(Date)==8:
# Date0 = Date[2:8]
#Date0=Date
# else:
# print('The input Date is invalid.')
# sys.exit(1)
#FileDir = downDir + '/' + downName
SAR_par='palsar_' +Date0 + '.par'
PROC_par='p' + Date0 + '.slc.par'
raw_out=Date0 + '.raw'
plot_data=Date0 +'.mlcc'
rspec_data=Date0 +'.rspec'
doppler_data=Date0 + '.dop'
rc_data=Date0 + '.rc'
autof_data=Date0 +'.autof'
slc_data=Date0 +'.slc'
slc_par=Date0 +'.slc.par'
call_str = 'PALSAR_proc ' + CEOS_SAR_leader + ' ' + SAR_par +' '+ PROC_par + ' '+ CEOS_raw_data + ' ' + raw_out + ' 0 0'
os.system(call_str)
palsar_ant_data='/home/chen/Software/InSAR/GAMMA/GAMMA_SOFTWARE-20180704/MSP/sensors/palsar_ant_20061024.dat'
call_str = 'cp ' + palsar_ant_data + ' .'
os.system(call_str)
call_str = 'PALSAR_antpat' + ' ' + SAR_par +' '+ PROC_par + ' ' + palsar_ant_data + ' palsar_antpat_msp.dat'
os.system(call_str)
call_str = 'doppler ' + SAR_par +' '+ PROC_par + ' ' + raw_out + ' ' + plot_data
os.system(call_str)
call_str = 'doppler ' + SAR_par +' '+ PROC_par + ' ' + raw_out + ' ' + doppler_data
os.system(call_str)
call_str = 'rspec_IQ ' + SAR_par +' '+ PROC_par + ' ' + raw_out + ' ' + rspec_data
os.system(call_str)
#call_str = 'rspec_JERS ' + SAR_par +' '+ PROC_par + ' ' + CEOS_raw_data + ' ' + rspec_data + ' - - - - - -'
#os.system(call_str)
call_str = 'pre_rc ' + SAR_par +' '+ PROC_par + ' ' + raw_out + ' ' + rc_data
os.system(call_str)
call_str = 'autof ' + SAR_par +' '+ PROC_par + ' ' + rc_data + ' ' + autof_data +' 5.0'
os.system(call_str)
call_str = 'autof ' + SAR_par +' '+ PROC_par + ' ' + rc_data + ' ' + autof_data +' 5.0'
os.system(call_str)
call_str = 'az_proc ' + SAR_par +' '+ PROC_par + ' ' + rc_data + ' ' + slc_data +' 16384'
os.system(call_str)
call_str = 'par_MSP ' + SAR_par +' '+ PROC_par + ' ' + slc_par
os.system(call_str)
else:
print('No data is found for date:' + Date)
sys.exit(1)
call_str ="rename 's/VV.SLC/slc/g' *"
os.system(call_str)
Date0 = Date
dataDir = slcDir + '/' + Date0
if not os.path.isdir(dataDir):
call_str = 'mkdir ' + dataDir
print('Generate SLC dir for date: ' + Date0)
os.system(call_str)
call_str = 'mv ' + Date0 + '.slc* ' + dataDir
os.system(call_str)
print("Down to SLC for %s is done! " % Date)
SslcImg = dataDir + '/'+ Date0 + '.slc'
SslcPar = dataDir + '/'+ Date0 + '.slc.par'
SamprlksImg = dataDir + '/'+ Date0 + '_' + rlks + 'rlks' + '.amp'
SamprlksPar = dataDir + '/'+ Date0 + '_' + rlks + 'rlks' + '.amp.par'
call_str = 'multi_look ' + SslcImg + ' ' + SslcPar + ' ' + SamprlksImg + ' ' + SamprlksPar + ' ' + rlks + ' ' + azlks
os.system(call_str)
nWidth = ut.read_gamma_par(SamprlksPar, 'read', 'range_samples')
call_str = 'raspwr ' + SamprlksImg + ' ' + str(nWidth)
os.system(call_str)
sys.exit(1)
if __name__ == '__main__':
main(sys.argv[:])
@@ -0,0 +1,307 @@
#! /usr/bin/env python
#'''
##################################################################################
# #
# Author: Yun-Meng Cao #
# Email : ymcmrs@gmail.com #
# Date : June, 2019 #
# #
# Generate SLC from SAR_IMS_P1 data #
# #
##################################################################################
#'''
import numpy as np
import os
import sys
import subprocess
import getopt
import time
import glob
def check_variable_name(path):
s=path.split("/")[0]
if len(s)>0 and s[0]=="$":
p0=os.getenv(s[1:])
path=path.replace(path.split("/")[0],p0)
return path
def read_template(File, delimiter='='):
'''Reads the template file into a python dictionary structure.
Input : string, full path to the template file
Output: dictionary, pysar template content
Example:
tmpl = read_template(KyushuT424F610_640AlosA.template)
tmpl = read_template(R1_54014_ST5_L0_F898.000.pi, ':')
'''
template_dict = {}
for line in open(File):
line = line.strip()
c = [i.strip() for i in line.split(delimiter, 1)] #split on the 1st occurrence of delimiter
if len(c) < 2 or line.startswith('%') or line.startswith('#'):
next #ignore commented lines or those without variables
else:
atrName = c[0]
atrValue = str.replace(c[1],'\n','').split("#")[0].strip()
atrValue = check_variable_name(atrValue)
template_dict[atrName] = atrValue
return template_dict
def UseGamma(inFile, task, keyword):
if task == "read":
f = open(inFile, "r")
while 1:
line = f.readline()
if not line: break
if line.count(keyword) == 1:
strtemp = line.split(":")
value = strtemp[1].strip()
return value
print("Keyword " + keyword + " doesn't exist in " + inFile)
f.close
def rm(TXT):
call_str = 'rm ' + TXT
os.system(call_str)
def usage():
print('''
******************************************************************************************************
Generate SLC and SLC_par file for ERS/ENVISAT (SAR_IMS_1P format)
usage:
Down2SLC_ASAR_Cat.py ProjectName DownName
e.g. Down2SLC_ASAR_Cat.py CotopaxiT120ERSA 910101
*******************************************************************************************************
''')
def main(argv):
if len(sys.argv)==3:
projectName = sys.argv[1]
Date = sys.argv[2]
else:
usage();sys.exit(1)
scratchDir = os.getenv('SCRATCHDIR')
templateDir = os.getenv('TEMPLATEDIR')
templateFile = templateDir + '/' + projectName + '.template'
templateContents=read_template(templateFile)
if 'rlks4cor' in templateContents: rlks4cor = templateContents['rlks4cor']
else: rlks4cor = '4'
if 'azlks4cor' in templateContents: azlks4cor = templateContents['azlks4cor']
else: azlks4cor = '4'
if 'rwin4cor' in templateContents: rwin4cor = templateContents['rwin4cor']
else: rwin4cor = '128'
if 'azwin4cor' in templateContents: azwin4cor = templateContents['azwin4cor']
else: azwin4cor = '128'
if 'rsample4cor' in templateContents: rsample4cor = templateContents['rsample4cor']
else: rsample4cor = '64'
if 'azsample4cor' in templateContents: azsample4cor = templateContents['azsample4cor']
else: azsample4cor = '64'
if ' rpos4cor' in templateContents: rpos4cor = templateContents[' rpos4cor']
else: rpos4cor = ' - '
if 'azpos4cor' in templateContents: azpos4cor = templateContents['azpos4cor']
else: azpos4cor = ' - '
if 'rfwin4cor' in templateContents: rfwin4cor = templateContents['rfwin4cor']
else: rfwin4cor = str(int(int(rwin4cor)/2))
if 'azfwin4cor' in templateContents: azfwin4cor = templateContents['azfwin4cor']
else: azfwin4cor = str(int(int(azwin4cor)/2))
if 'rfsample4cor' in templateContents: rfsample4cor = templateContents['rfsample4cor']
else: rfsample4cor = str(2*int(rsample4cor))
if 'azfsample4cor' in templateContents: azfsample4cor = templateContents['azfsample4cor']
else: azfsample4cor = str(2*int(azsample4cor))
if 'thresh4cor' in templateContents: thresh4cor = templateContents['thresh4cor']
else: thresh4cor = ' 0.2 '
rlks = templateContents['Range_Looks']
azlks = templateContents['Azimuth_Looks']
projectDir = scratchDir + '/' + projectName
downDir = scratchDir + '/' + projectName + "/DOWNLOAD"
slcDir = scratchDir + '/' + projectName + '/SLC'
if not os.path.isdir(slcDir):
call_str= 'mkdir ' +slcDir
os.system(call_str)
os.chdir(downDir)
t0 = 't0_' + Date
call_str = 'ls >' + t0
os.system(call_str)
tt = 'tt_' + Date
call_str = "grep " + Date + ' ' + t0 + '> ' + tt
os.system(call_str)
te = 'te_' + Date
call_str = "grep ASA_IMS_1P " + tt + " > " + te
os.system(call_str)
AA= np.loadtxt(te,dtype=np.str)
Na = AA.size
AA=AA.reshape(Na,)
for i in range(Na):
Date0 = Date+'_' + str(i)
downName = str(AA[i])
FileDir = downDir + '/' + downName
call_str = 'par_ASAR '+ FileDir + ' ' + Date0
os.system(call_str)
call_str ="rename 's/VV.SLC/slc/g' *"
os.system(call_str)
slcpar = Date0 + '.slc.par'
call_str = 'ASAR_orb_cor_par.py ' + slcpar
os.system(call_str)
Date0 = Date
if len(Date)==6:
Date0 = Date
Date6 = Date
elif len(Date)==8:
Date0 = Date[2:8]
Date6 = Date[2:8]
else:
print('The input Date is invalid.')
sys.exit(1)
dataDir = slcDir + '/' + Date0
if not os.path.isdir(dataDir):
call_str = 'mkdir ' + dataDir
print('Generate SLC dir for date: ' + Date0)
os.system(call_str)
call_str = 'mv ' + Date + '*.slc* ' + dataDir
os.system(call_str)
os.chdir(dataDir)
for i in range(Na):
Date0 = Date+'_' + str(i)
downName = str(AA[i])
SLCm = Date0 + '.slc'
SLCm_par = Date0 + '.slc.par'
MamprlksImg = Date0 + '.amp'
MamprlksPar = Date0 + '.amp.par'
call_str = 'multi_look ' + SLCm + ' ' + SLCm_par + ' ' + MamprlksImg + ' ' + MamprlksPar + ' ' + rlks + ' ' + azlks
os.system(call_str)
nWidth = UseGamma(MamprlksPar, 'read', 'range_samples')
call_str = 'raspwr ' + MamprlksImg + ' ' + nWidth
os.system(call_str)
SLC = Date6+'.slc'
SLCPAR = Date6 + '.slc.par'
AMP = Date6+'.amp'
AMPPAR = Date6+'.amp.par'
if Na==1:
os.rename(SLCm,SLC)
os.rename(SLCm_par,SLCPAR)
os.rename(MamprlksImg,AMP)
os.rename(MamprlksPar,AMPPAR)
for i in range(Na-1):
if i==0:
DateA = Date + '_0'
else:
DateA = Date + '_' + str(i-1) + str(i)
SLCA = DateA + '.slc'
SLCA_par = DateA + '.slc.par'
DateB = Date + '_' +str(i+1)
SLCB = DateB + '.slc'
SLCB_par = DateB + '.slc.par'
DateC = Date + '_' + str(i) + str(i+1)
SLCC = DateC + '.slc'
SLCC_par = DateC + '.slc.par'
#####################################################################################
MamprlksImg = Date + '.amp'
MamprlksPar = Date + '.amp.par'
off = DateC + '.off'
offs = DateC + '.offs'
offsets = DateC + '.offsets'
coffs = DateC + '.coffs'
coffsets = DateC + '.coffsets'
snr = DateC + '.snr'
off_std = DateC + '.off_std'
########################## Generate off file #############################
call_str = "create_offset " + SLCA_par + " " + SLCB_par + " " + off + " 1 - - 0"
os.system(call_str)
call_str = 'init_offset_orbit '+ SLCA_par + " " + SLCB_par + ' ' + off
os.system(call_str)
call_str = 'init_offset '+ SLCA + ' ' + SLCB + ' ' + SLCA_par + ' ' + SLCB_par + ' ' + off + ' ' + rlks4cor + ' ' + azlks4cor + ' ' + rpos4cor + ' ' + azpos4cor
os.system(call_str)
call_str = 'init_offset '+ SLCA + ' ' + SLCB + ' ' + SLCA_par + ' ' + SLCB_par + ' ' + off + ' 1 1 - - '
os.system(call_str)
call_str = "offset_pwr " + SLCA + " " + SLCB + " " + SLCA_par + " " + SLCB_par + " " + off + " " + offs + " " + snr + " " + rwin4cor + " " + azwin4cor + " " + offsets + " 2 "+ rsample4cor + " " + azsample4cor
os.system(call_str)
call_str = "offset_fit " + offs + " " + snr + " " + off + " " + coffs + " " + coffsets + " " + thresh4cor +" 3"
os.system(call_str)
call_str = "offset_pwr " +SLCA + " " + SLCB + " " + SLCA_par + " " + SLCB_par + " " + off + " " + offs + " " + snr + " " + rfwin4cor + " " + azfwin4cor + " " + offsets + " 2 " + rfsample4cor + " " + azfsample4cor
os.system(call_str)
call_str = "offset_fit " + offs + " " + snr + " " + off + " " + coffs + " " + coffsets + " " + thresh4cor + " 4 >" + off_std
os.system(call_str)
########################################################################################
call_str = 'SLC_cat ' + SLCA + ' ' + SLCB + ' ' + SLCA_par + ' ' + SLCB_par + ' ' + off + ' ' + SLCC + ' ' + SLCC_par
os.system(call_str)
if i==(Na-2):
if len(Date)==6:
DD = Date
else:
DD = Date[2:8]
SLCm = DD + '.slc'
SLCm_par = DD + '.slc.par'
call_str = 'cp ' + SLCC + ' ' + SLCm
os.system(call_str)
call_str = 'cp ' + SLCC_par + ' ' + SLCm_par
os.system(call_str)
call_str = 'multi_look ' + SLCm + ' ' + SLCm_par + ' ' + MamprlksImg + ' ' + MamprlksPar + ' ' + rlks + ' ' + azlks
os.system(call_str)
nWidth = UseGamma(MamprlksPar, 'read', 'range_samples')
call_str = 'raspwr ' + MamprlksImg + ' ' + nWidth
os.system(call_str)
call_str = 'rm *.amp'
os.system(call_str)
call_str = 'rm *_*.slc'
os.system(call_str)
print("Down to SLC for %s is done! " % Date)
sys.exit(1)
if __name__ == '__main__':
main(sys.argv[:])
@@ -0,0 +1,136 @@
#! /usr/bin/env python
#'''
##################################################################################
# #
# Author: Yun-Meng Cao #
# Email : ymcmrs@gmail.com #
# Date : March, 2017 #
# #
# Generate Sentinel SLC from the downloaded data #
# #
##################################################################################
#'''
import numpy as np
import os
import sys
import subprocess
import getopt
import time
import glob
def check_variable_name(path):
s=path.split("/")[0]
if len(s)>0 and s[0]=="$":
p0=os.getenv(s[1:])
path=path.replace(path.split("/")[0],p0)
return path
def read_template(File, delimiter='='):
'''Reads the template file into a python dictionary structure.
Input : string, full path to the template file
Output: dictionary, pysar template content
Example:
tmpl = read_template(KyushuT424F610_640AlosA.template)
tmpl = read_template(R1_54014_ST5_L0_F898.000.pi, ':')
'''
template_dict = {}
for line in open(File):
line = line.strip()
c = [i.strip() for i in line.split(delimiter, 1)] #split on the 1st occurrence of delimiter
if len(c) < 2 or line.startswith('%') or line.startswith('#'):
next #ignore commented lines or those without variables
else:
atrName = c[0]
atrValue = str.replace(c[1],'\n','').split("#")[0].strip()
atrValue = check_variable_name(atrValue)
template_dict[atrName] = atrValue
return template_dict
def UseGamma(inFile, task, keyword):
if task == "read":
f = open(inFile, "r")
while 1:
line = f.readline()
if not line: break
if line.count(keyword) == 1:
strtemp = line.split(":")
value = strtemp[1].strip()
return value
print("Keyword " + keyword + " doesn't exist in " + inFile)
f.close
def rm(TXT):
call_str = 'rm ' + TXT
os.system(call_str)
def usage():
print('''
******************************************************************************************************
Downloading Sentinel-1A/B data based on ssara
usage:
Down2SLC_ERS_Cat_All.py ProjectName
e.g. Down2SLC_ERS_Cat_All.py CotopaxiT120ERSA
*******************************************************************************************************
''')
def main(argv):
if len(sys.argv)==2:
projectName = sys.argv[1]
else:
usage();sys.exit(1)
scratchDir = os.getenv('SCRATCHDIR')
templateDir = os.getenv('TEMPLATEDIR')
projectDir = scratchDir + '/' + projectName
downDir = scratchDir + '/' + projectName + "/DOWNLOAD"
slcDir = scratchDir + '/' + projectName + '/SLC'
if not os.path.isdir(slcDir):
call_str= 'mkdir ' +slcDir
os.system(call_str)
os.chdir(downDir)
call_str = 'ls > tt0'
os.system(call_str)
call_str = 'grep ASA_IMS_1P tt0 >tt1'
os.system(call_str)
call_str = "awk -F_ '{print $3}' tt1 > tt2 "
os.system(call_str)
call_str = "awk -FSA '{print $2}' tt2 > ttt"
os.system(call_str)
call_str = 'sort ttt | uniq > ttm'
os.system(call_str)
AA= np.loadtxt('ttm',dtype=np.str)
Na = AA.size
for i in range(Na):
call_str = 'Down2SLC_ASAR_Cat.py ' + projectName + ' ' + AA[i]
print(call_str)
call_str = 'Down2SLC_ASAR_Cat.py ' + projectName + ' ' + AA[i] + ' >/dev/null'
os.system(call_str)
print("Down to SLC for %s is done! " % projectName)
sys.exit(1)
if __name__ == '__main__':
main(sys.argv[:])
@@ -0,0 +1,155 @@
#! /usr/bin/env python
#'''
##################################################################################
# #
# Author: Yun-Meng Cao #
# Email : ymcmrs@gmail.com #
# Date : June, 2019 #
# #
# Generate SLC from SAR_IMS_P1 data #
# #
##################################################################################
#'''
import numpy as np
import os
import sys
import subprocess
import getopt
import time
import glob
def check_variable_name(path):
s=path.split("/")[0]
if len(s)>0 and s[0]=="$":
p0=os.getenv(s[1:])
path=path.replace(path.split("/")[0],p0)
return path
def read_template(File, delimiter='='):
'''Reads the template file into a python dictionary structure.
Input : string, full path to the template file
Output: dictionary, pysar template content
Example:
tmpl = read_template(KyushuT424F610_640AlosA.template)
tmpl = read_template(R1_54014_ST5_L0_F898.000.pi, ':')
'''
template_dict = {}
for line in open(File):
line = line.strip()
c = [i.strip() for i in line.split(delimiter, 1)] #split on the 1st occurrence of delimiter
if len(c) < 2 or line.startswith('%') or line.startswith('#'):
next #ignore commented lines or those without variables
else:
atrName = c[0]
atrValue = str.replace(c[1],'\n','').split("#")[0].strip()
atrValue = check_variable_name(atrValue)
template_dict[atrName] = atrValue
return template_dict
def UseGamma(inFile, task, keyword):
if task == "read":
f = open(inFile, "r")
while 1:
line = f.readline()
if not line: break
if line.count(keyword) == 1:
strtemp = line.split(":")
value = strtemp[1].strip()
return value
print("Keyword " + keyword + " doesn't exist in " + inFile)
f.close
def rm(TXT):
call_str = 'rm ' + TXT
os.system(call_str)
def usage():
print('''
******************************************************************************************************
Generate SLC and SLC_par file for ERS/ENVISAT (SAR_IMS_1P format)
usage:
Down2SLC_ERS.py ProjectName DownName
e.g. Down2SLC_ERS.py CotopaxiT120ERSA 910101
*******************************************************************************************************
''')
def main(argv):
if len(sys.argv)==3:
projectName = sys.argv[1]
Date = sys.argv[2]
else:
usage();sys.exit(1)
scratchDir = os.getenv('SCRATCHDIR')
templateDir = os.getenv('TEMPLATEDIR')
projectDir = scratchDir + '/' + projectName
downDir = scratchDir + '/' + projectName + "/DOWNLOAD"
slcDir = scratchDir + '/' + projectName + '/SLC'
if not os.path.isdir(slcDir):
call_str= 'mkdir ' +slcDir
os.system(call_str)
os.chdir(downDir)
t0 = 't0_' + Date
call_str = 'ls >' + t0
os.system(call_str)
tt = 'tt_' + Date
call_str = "grep " + Date + ' ' + t0 + '> ' + tt
os.system(call_str)
te = 'te_' + Date
call_str = "grep SAR_IMS_1P " + tt + " > " + te
os.system(call_str)
AA= np.loadtxt(te,dtype=np.str)
Na = AA.size
if Na > 0:
downName = str(AA[0])
FileDir = downDir + '/' + downName
call_str = 'par_ASAR '+ FileDir + ' ' + Date
os.system(call_str)
else:
print('No data is found for date:' + Date)
sys.exit(1)
call_str ="rename 's/VV.SLC/slc/g' *"
os.system(call_str)
Date0 = Date
if len(Date)==6:
Date0 = Date
elif len(Date)==8:
Date0 = Date[2:8]
else:
print('The input Date is invalid.')
sys.exit(1)
dataDir = slcDir + '/' + Date0
if not os.path.isdir(dataDir):
call_str = 'mkdir ' + dataDir
print('Generate SLC dir for date: ' + Date0)
os.system(call_str)
call_str = 'mv ' + Date + '.slc* ' + dataDir
os.system(call_str)
print("Down to SLC for %s is done! " % Date)
sys.exit(1)
if __name__ == '__main__':
main(sys.argv[:])
@@ -0,0 +1,229 @@
#! /usr/bin/env python
#'''
##################################################################################
# #
# Author: Yun-Meng Cao #
# Email : ymcmrs@gmail.com #
# Date : March, 2017 #
# #
# Generate Sentinel SLC from the downloaded data #
# #
##################################################################################
#'''
import numpy as np
import os
import sys
import subprocess
import getopt
import time
import glob
def check_variable_name(path):
s=path.split("/")[0]
if len(s)>0 and s[0]=="$":
p0=os.getenv(s[1:])
path=path.replace(path.split("/")[0],p0)
return path
def read_template(File, delimiter='='):
'''Reads the template file into a python dictionary structure.
Input : string, full path to the template file
Output: dictionary, pysar template content
Example:
tmpl = read_template(KyushuT424F610_640AlosA.template)
tmpl = read_template(R1_54014_ST5_L0_F898.000.pi, ':')
'''
template_dict = {}
for line in open(File):
line = line.strip()
c = [i.strip() for i in line.split(delimiter, 1)] #split on the 1st occurrence of delimiter
if len(c) < 2 or line.startswith('%') or line.startswith('#'):
next #ignore commented lines or those without variables
else:
atrName = c[0]
atrValue = str.replace(c[1],'\n','').split("#")[0].strip()
atrValue = check_variable_name(atrValue)
template_dict[atrName] = atrValue
return template_dict
def UseGamma(inFile, task, keyword):
if task == "read":
f = open(inFile, "r")
while 1:
line = f.readline()
if not line: break
if line.count(keyword) == 1:
strtemp = line.split(":")
value = strtemp[1].strip()
return value
print("Keyword " + keyword + " doesn't exist in " + inFile)
f.close
def rm(TXT):
call_str = 'rm ' + TXT
os.system(call_str)
def usage():
print('''
******************************************************************************************************
Downloading Sentinel-1A/B data based on ssara
usage:
Down2SLC_Sen_Gamma.py ProjectName DownName
e.g. Down2SLC_Sen_Gamma.py CotopaxiT120SenVVA 170118
*******************************************************************************************************
''')
def main(argv):
if len(sys.argv)==3:
projectName = sys.argv[1]
Date = sys.argv[2]
else:
usage();sys.exit(1)
scratchDir = os.getenv('SCRATCHDIR')
templateDir = os.getenv('TEMPLATEDIR')
projectDir = scratchDir + '/' + projectName
downDir = scratchDir + '/' + projectName + "/DOWNLOAD"
slcDir = scratchDir + '/' + projectName + '/SLC'
if not os.path.isdir(slcDir):
call_str= 'mkdir ' +slcDir
os.system(call_str)
os.chdir(downDir)
t0 = 't0_' + Date
call_str = 'ls >' + t0
os.system(call_str)
tt = 'tt_' + Date
call_str = "grep " + Date + ' ' + t0 + '> ' + tt
os.system(call_str)
ts = 'ts_' + Date
call_str = "grep SAFE " + tt + ' >' + ts
os.system(call_str)
tz = 'tz_' + Date
call_str = "grep zip " + tt + " > " + tz
os.system(call_str)
A1= np.loadtxt(ts,dtype=np.str)
Na1 = A1.size
A2= np.loadtxt(tz,dtype=np.str)
Na2 = A2.size
rm(t0);rm(tt);rm(ts);rm(tz)
if Na1 == 0:
if Na2 > 0:
if Na2 == 1:
downName = str(A2)
else:
downName = str(A2[0])
FileDir = downDir + '/' + downName
RAWNAME = downName.split('.')[0]+'.SAFE'
call_str = 'unzip '+ FileDir
os.system(call_str)
else:
if Na1 == 1:
RAWNAME = str(A1)
else:
RAWNAME = str(A1[0])
print(RAWNAME)
RAWFILEDir = downDir + '/'+str(RAWNAME)
Date = RAWNAME[19:25]
DateDir = slcDir + '/'+Date
if not os.path.isdir(DateDir):
call_str='mkdir '+DateDir
os.system(call_str)
measureDir = RAWFILEDir + '/measurement'
annotatDir = RAWFILEDir + '/annotation'
calibraDir = RAWFILEDir + '/annotation/calibration'
MM = glob.glob(measureDir + '/*vv*tiff')
# MEASURE = glob.glob(measureDir + '/*vv*tiff')
# ANNOTAT = glob.glob(annotatDir + '/*vv*xml' )
# CALIBRA = glob.glob(calibraDir+'/calibration*vv*')
# NOISE = glob.glob(calibraDir+'/noise*vv*')
SLC_Tab = DateDir + '/' + Date+'_SLC_Tab'
TEST = DateDir + '/' + Date + '.IW1.slc'
if not os.path.isfile(TEST):
if os.path.isfile(SLC_Tab):
os.remove(SLC_Tab)
for kk in range(len(MM)):
SLC = DateDir + '/' + Date + '.IW' + str(kk+1)+'.slc'
SLCPar = DateDir + '/' + Date + '.IW' + str(kk+1)+'.slc.par'
TOPPar = DateDir + '/' + Date + '.IW' + str(kk+1)+'.slc.TOPS_par'
BURST = DateDir + '/' + Date + '.IW' + str(kk+1)+'.burst.par'
if os.path.isfile(BURST):
os.remove(BURST)
call_str = 'echo ' + SLC + ' ' + SLCPar + ' ' + TOPPar + ' >> ' + SLC_Tab
os.system(call_str)
MEASURE = glob.glob(measureDir + '/*iw' + str(kk+1) + '*vv*tiff')
ANNOTAT = glob.glob(annotatDir + '/*iw' + str(kk+1) + '*vv*xml' )
CALIBRA = glob.glob(calibraDir+'/calibration*'+ 'iw' + str(kk+1) + '*vv*')
NOISE = glob.glob(calibraDir+'/noise*' + 'iw' + str(kk+1) + '*vv*')
#call_str = 'S1_burstloc ' + ANNOTAT[0] + '> ' +BURST
#os.system(call_str)
if int(Date) > 180311:
call_str = 'par_S1_SLC ' + MEASURE[0] + ' ' + ANNOTAT[0] + ' ' + CALIBRA[0] + ' - ' + SLCPar + ' ' + SLC + ' ' + TOPPar
else:
call_str = 'par_S1_SLC ' + MEASURE[0] + ' ' + ANNOTAT[0] + ' ' + CALIBRA[0] + ' ' + NOISE[0] + ' ' + SLCPar + ' ' + SLC + ' ' + TOPPar
os.system(call_str)
call_str = 'SLC_burst_corners ' + SLCPar + ' ' + TOPPar + ' > ' +BURST
os.system(call_str)
TSLC = DateDir + '/' + Date + '.slc'
TSLCPar = DateDir + '/' + Date + '.slc.par'
TMLI = DateDir + '/' + Date + '_20rlks.amp'
TMLIPar = DateDir + '/' + Date + '_20rlks.amp.par'
call_str = 'SLC_mosaic_S1_TOPS ' + SLC_Tab + ' ' + TSLC + ' ' + TSLCPar + ' 10 2'
os.system(call_str)
call_str = 'multi_look ' + TSLC + ' ' + TSLCPar + ' ' + TMLI + ' ' + TMLIPar + ' 20 4'
os.system(call_str)
nWidth = UseGamma(TMLIPar, 'read','range_samples:')
call_str = 'raspwr ' + TMLI + ' ' + nWidth + ' - - - - - - - '
os.system(call_str)
call_str = 'rm -rf ' + RAWFILEDir
os.system(call_str)
print("Down to SLC for %s is done! " % Date)
sys.exit(1)
if __name__ == '__main__':
main(sys.argv[:])
@@ -0,0 +1,306 @@
#! /usr/bin/env python
#'''
##################################################################################
# #
# Author: Yun-Meng Cao #
# Email : ymcmrs@gmail.com #
# Date : June, 2019 #
# #
# Generate SLC from SAR_IMS_P1 data #
# #
##################################################################################
#'''
import numpy as np
import os
import sys
import subprocess
import getopt
import time
import glob
def check_variable_name(path):
s=path.split("/")[0]
if len(s)>0 and s[0]=="$":
p0=os.getenv(s[1:])
path=path.replace(path.split("/")[0],p0)
return path
def read_template(File, delimiter='='):
'''Reads the template file into a python dictionary structure.
Input : string, full path to the template file
Output: dictionary, pysar template content
Example:
tmpl = read_template(KyushuT424F610_640AlosA.template)
tmpl = read_template(R1_54014_ST5_L0_F898.000.pi, ':')
'''
template_dict = {}
for line in open(File):
line = line.strip()
c = [i.strip() for i in line.split(delimiter, 1)] #split on the 1st occurrence of delimiter
if len(c) < 2 or line.startswith('%') or line.startswith('#'):
next #ignore commented lines or those without variables
else:
atrName = c[0]
atrValue = str.replace(c[1],'\n','').split("#")[0].strip()
atrValue = check_variable_name(atrValue)
template_dict[atrName] = atrValue
return template_dict
def UseGamma(inFile, task, keyword):
if task == "read":
f = open(inFile, "r")
while 1:
line = f.readline()
if not line: break
if line.count(keyword) == 1:
strtemp = line.split(":")
value = strtemp[1].strip()
return value
print("Keyword " + keyword + " doesn't exist in " + inFile)
f.close
def rm(TXT):
call_str = 'rm ' + TXT
os.system(call_str)
def usage():
print('''
******************************************************************************************************
Generate SLC and SLC_par file for ERS/ENVISAT (SAR_IMS_1P format)
usage:
Down2SLC_ERS.py ProjectName DownName
e.g. Down2SLC_ERS.py CotopaxiT120ERSA 910101
*******************************************************************************************************
''')
def main(argv):
if len(sys.argv)==3:
projectName = sys.argv[1]
Date = sys.argv[2]
else:
usage();sys.exit(1)
scratchDir = os.getenv('SCRATCHDIR')
templateDir = os.getenv('TEMPLATEDIR')
templateFile = templateDir + '/' + projectName + '.template'
templateContents=read_template(templateFile)
if 'rlks4cor' in templateContents: rlks4cor = templateContents['rlks4cor']
else: rlks4cor = '4'
if 'azlks4cor' in templateContents: azlks4cor = templateContents['azlks4cor']
else: azlks4cor = '4'
if 'rwin4cor' in templateContents: rwin4cor = templateContents['rwin4cor']
else: rwin4cor = '128'
if 'azwin4cor' in templateContents: azwin4cor = templateContents['azwin4cor']
else: azwin4cor = '128'
if 'rsample4cor' in templateContents: rsample4cor = templateContents['rsample4cor']
else: rsample4cor = '64'
if 'azsample4cor' in templateContents: azsample4cor = templateContents['azsample4cor']
else: azsample4cor = '64'
if ' rpos4cor' in templateContents: rpos4cor = templateContents[' rpos4cor']
else: rpos4cor = ' - '
if 'azpos4cor' in templateContents: azpos4cor = templateContents['azpos4cor']
else: azpos4cor = ' - '
if 'rfwin4cor' in templateContents: rfwin4cor = templateContents['rfwin4cor']
else: rfwin4cor = str(int(int(rwin4cor)/2))
if 'azfwin4cor' in templateContents: azfwin4cor = templateContents['azfwin4cor']
else: azfwin4cor = str(int(int(azwin4cor)/2))
if 'rfsample4cor' in templateContents: rfsample4cor = templateContents['rfsample4cor']
else: rfsample4cor = str(2*int(rsample4cor))
if 'azfsample4cor' in templateContents: azfsample4cor = templateContents['azfsample4cor']
else: azfsample4cor = str(2*int(azsample4cor))
if 'thresh4cor' in templateContents: thresh4cor = templateContents['thresh4cor']
else: thresh4cor = ' 0.2 '
rlks = templateContents['Range_Looks']
azlks = templateContents['Azimuth_Looks']
projectDir = scratchDir + '/' + projectName
downDir = scratchDir + '/' + projectName + "/DOWNLOAD"
slcDir = scratchDir + '/' + projectName + '/SLC'
if not os.path.isdir(slcDir):
call_str= 'mkdir ' +slcDir
os.system(call_str)
os.chdir(downDir)
t0 = 't0_' + Date
call_str = 'ls >' + t0
os.system(call_str)
tt = 'tt_' + Date
call_str = "grep " + Date + ' ' + t0 + '> ' + tt
os.system(call_str)
te = 'te_' + Date
call_str = "grep SAR_IMS_1P " + tt + " > " + te
os.system(call_str)
AA= np.loadtxt(te,dtype=np.str)
Na = AA.size
AA=AA.reshape(Na,)
for i in range(Na):
Date0 = Date+'_' + str(i)
downName = str(AA[i])
FileDir = downDir + '/' + downName
call_str = 'par_ASAR '+ FileDir + ' ' + Date0
os.system(call_str)
call_str ="rename 's/VV.SLC/slc/g' *"
os.system(call_str)
slcpar = Date0 + '.slc.par'
call_str = 'ERS_orb_cor_par.py ' + slcpar
os.system(call_str)
Date0 = Date
if len(Date)==6:
Date6 = Date
Date0 = Date
elif len(Date)==8:
Date0 = Date[2:8]
Date6 = Date[2:8]
else:
print('The input Date is invalid.')
sys.exit(1)
dataDir = slcDir + '/' + Date0
if not os.path.isdir(dataDir):
call_str = 'mkdir ' + dataDir
print('Generate SLC dir for date: ' + Date0)
os.system(call_str)
call_str = 'mv ' + Date + '*.slc* ' + dataDir
os.system(call_str)
os.chdir(dataDir)
for i in range(Na):
Date0 = Date+'_' + str(i)
downName = str(AA[i])
SLCm = Date0 + '.slc'
SLCm_par = Date0 + '.slc.par'
MamprlksImg = Date0 + '.amp'
MamprlksPar = Date0 + '.amp.par'
call_str = 'multi_look ' + SLCm + ' ' + SLCm_par + ' ' + MamprlksImg + ' ' + MamprlksPar + ' ' + rlks + ' ' + azlks
os.system(call_str)
nWidth = UseGamma(MamprlksPar, 'read', 'range_samples')
call_str = 'raspwr ' + MamprlksImg + ' ' + nWidth
os.system(call_str)
SLC = Date6+'.slc'
SLCPAR = Date6 + '.slc.par'
AMP = Date6+'.amp'
AMPPAR = Date6+'.amp.par'
if Na==1:
os.rename(SLCm,SLC)
os.rename(SLCm_par,SLCPAR)
os.rename(MamprlksImg,AMP)
os.rename(MamprlksPar,AMPPAR)
for i in range(Na-1):
if i==0:
DateA = Date + '_0'
else:
DateA = Date + '_' + str(i-1) + str(i)
SLCA = DateA + '.slc'
SLCA_par = DateA + '.slc.par'
DateB = Date + '_' +str(i+1)
SLCB = DateB + '.slc'
SLCB_par = DateB + '.slc.par'
DateC = Date + '_' + str(i) + str(i+1)
SLCC = DateC + '.slc'
SLCC_par = DateC + '.slc.par'
#####################################################################################
MamprlksImg = Date + '.amp'
MamprlksPar = Date + '.amp.par'
off = DateC + '.off'
offs = DateC + '.offs'
offsets = DateC + '.offsets'
coffs = DateC + '.coffs'
coffsets = DateC + '.coffsets'
snr = DateC + '.snr'
off_std = DateC + '.off_std'
########################## Generate off file #############################
call_str = "create_offset " + SLCA_par + " " + SLCB_par + " " + off + " 1 - - 0"
os.system(call_str)
call_str = 'init_offset_orbit '+ SLCA_par + " " + SLCB_par + ' ' + off
os.system(call_str)
call_str = 'init_offset '+ SLCA + ' ' + SLCB + ' ' + SLCA_par + ' ' + SLCB_par + ' ' + off + ' ' + rlks4cor + ' ' + azlks4cor + ' ' + rpos4cor + ' ' + azpos4cor
os.system(call_str)
call_str = 'init_offset '+ SLCA + ' ' + SLCB + ' ' + SLCA_par + ' ' + SLCB_par + ' ' + off + ' 1 1 - - '
os.system(call_str)
call_str = "offset_pwr " + SLCA + " " + SLCB + " " + SLCA_par + " " + SLCB_par + " " + off + " " + offs + " " + snr + " " + rwin4cor + " " + azwin4cor + " " + offsets + " 2 "+ rsample4cor + " " + azsample4cor
os.system(call_str)
call_str = "offset_fit " + offs + " " + snr + " " + off + " " + coffs + " " + coffsets + " " + thresh4cor +" 3"
os.system(call_str)
call_str = "offset_pwr " +SLCA + " " + SLCB + " " + SLCA_par + " " + SLCB_par + " " + off + " " + offs + " " + snr + " " + rfwin4cor + " " + azfwin4cor + " " + offsets + " 2 " + rfsample4cor + " " + azfsample4cor
os.system(call_str)
call_str = "offset_fit " + offs + " " + snr + " " + off + " " + coffs + " " + coffsets + " " + thresh4cor + " 4 >" + off_std
os.system(call_str)
########################################################################################
call_str = 'SLC_cat ' + SLCA + ' ' + SLCB + ' ' + SLCA_par + ' ' + SLCB_par + ' ' + off + ' ' + SLCC + ' ' + SLCC_par
os.system(call_str)
if i==(Na-2):
if len(Date)==6:
DD = Date
else:
DD = Date[2:8]
SLCm = DD + '.slc'
SLCm_par = DD + '.slc.par'
call_str = 'cp ' + SLCC + ' ' + SLCm
os.system(call_str)
call_str = 'cp ' + SLCC_par + ' ' + SLCm_par
os.system(call_str)
call_str = 'multi_look ' + SLCm + ' ' + SLCm_par + ' ' + MamprlksImg + ' ' + MamprlksPar + ' ' + rlks + ' ' + azlks
os.system(call_str)
nWidth = UseGamma(MamprlksPar, 'read', 'range_samples')
call_str = 'raspwr ' + MamprlksImg + ' ' + nWidth
os.system(call_str)
call_str = 'rm *.amp'
os.system(call_str)
call_str = 'rm *_*.slc'
os.system(call_str)
print("Down to SLC for %s is done! " % Date)
sys.exit(1)
if __name__ == '__main__':
main(sys.argv[:])
@@ -0,0 +1,136 @@
#! /usr/bin/env python
#'''
##################################################################################
# #
# Author: Yun-Meng Cao #
# Email : ymcmrs@gmail.com #
# Date : March, 2017 #
# #
# Generate Sentinel SLC from the downloaded data #
# #
##################################################################################
#'''
import numpy as np
import os
import sys
import subprocess
import getopt
import time
import glob
def check_variable_name(path):
s=path.split("/")[0]
if len(s)>0 and s[0]=="$":
p0=os.getenv(s[1:])
path=path.replace(path.split("/")[0],p0)
return path
def read_template(File, delimiter='='):
'''Reads the template file into a python dictionary structure.
Input : string, full path to the template file
Output: dictionary, pysar template content
Example:
tmpl = read_template(KyushuT424F610_640AlosA.template)
tmpl = read_template(R1_54014_ST5_L0_F898.000.pi, ':')
'''
template_dict = {}
for line in open(File):
line = line.strip()
c = [i.strip() for i in line.split(delimiter, 1)] #split on the 1st occurrence of delimiter
if len(c) < 2 or line.startswith('%') or line.startswith('#'):
next #ignore commented lines or those without variables
else:
atrName = c[0]
atrValue = str.replace(c[1],'\n','').split("#")[0].strip()
atrValue = check_variable_name(atrValue)
template_dict[atrName] = atrValue
return template_dict
def UseGamma(inFile, task, keyword):
if task == "read":
f = open(inFile, "r")
while 1:
line = f.readline()
if not line: break
if line.count(keyword) == 1:
strtemp = line.split(":")
value = strtemp[1].strip()
return value
print("Keyword " + keyword + " doesn't exist in " + inFile)
f.close
def rm(TXT):
call_str = 'rm ' + TXT
os.system(call_str)
def usage():
print('''
******************************************************************************************************
Downloading Sentinel-1A/B data based on ssara
usage:
Down2SLC_ERS_Cat_All.py ProjectName
e.g. Down2SLC_ERS_Cat_All.py CotopaxiT120ERSA
*******************************************************************************************************
''')
def main(argv):
if len(sys.argv)==2:
projectName = sys.argv[1]
else:
usage();sys.exit(1)
scratchDir = os.getenv('SCRATCHDIR')
templateDir = os.getenv('TEMPLATEDIR')
projectDir = scratchDir + '/' + projectName
downDir = scratchDir + '/' + projectName + "/DOWNLOAD"
slcDir = scratchDir + '/' + projectName + '/SLC'
if not os.path.isdir(slcDir):
call_str= 'mkdir ' +slcDir
os.system(call_str)
os.chdir(downDir)
call_str = 'ls > tt0'
os.system(call_str)
call_str = 'grep SAR_IMS_1P tt0 >tt1'
os.system(call_str)
call_str = "awk -F_ '{print $3}' tt1 > tt2 "
os.system(call_str)
call_str = "awk -FSA '{print $2}' tt2 > ttt"
os.system(call_str)
call_str = 'sort ttt | uniq > ttm'
os.system(call_str)
AA= np.loadtxt('ttm',dtype=np.str)
Na = AA.size
for i in range(Na):
call_str = 'Down2SLC_ERS_Cat.py ' + projectName + ' ' + AA[i]
print(call_str)
call_str = 'Down2SLC_ERS_Cat.py ' + projectName + ' ' + AA[i] + ' >/dev/null'
os.system(call_str)
print("Down to SLC for %s is done! " % projectName)
sys.exit(1)
if __name__ == '__main__':
main(sys.argv[:])
@@ -0,0 +1,206 @@
#! /usr/bin/env python
#################################################################
### This program is part of PyINT v1.0 ###
### Copy Right (c): 2017, Yunmeng Cao ###
### Author: Yunmeng Cao ###
### Email : ymcmrs@gmail.com ###
### Univ. : Central South University & University of Miami ###
#################################################################
import numpy as np
import os
import sys
import subprocess
import getopt
import time
import glob
import argparse
import linecache
def StrNum(S):
S = str(S)
if len(S)==1:
S='0' +S
return S
def UseGamma(inFile, task, keyword):
if task == "read":
f = open(inFile, "r")
while 1:
line = f.readline()
if not line: break
if line.count(keyword) == 1:
strtemp = line.split(":")
value = strtemp[1].strip()
return value
print("Keyword " + keyword + " doesn't exist in " + inFile)
f.close()
#########################################################################
INTRODUCTION = '''
#############################################################################
Copy Right(c): 2017-2019, Yunmeng Cao @PyINT v1.0
Download precise ERS orbit data from Delft (http://www.deos.tudelft.nl/).
Correct the orbit parameters using DELFT_vec2
ftp://dutlru2.lr.tudelft.nl/pub/orbits/ODR.ERS-2/dgm-e04/arclist
'''
EXAMPLE = '''
Usage:
ERS_DEOS.py projectName Date
Examples:
ERS_DEOS.py AqabaERSA 960101
##############################################################################
'''
def cmdLineParse():
parser = argparse.ArgumentParser(description='Download (and correct) precise ERS orbit data.',\
formatter_class=argparse.RawTextHelpFormatter,\
epilog=INTRODUCTION+'\n'+EXAMPLE)
parser.add_argument('projectName',help='project name')
parser.add_argument('date',help='date of the ERS data')
inps = parser.parse_args()
return inps
################################################################################
def main(argv):
total = time.time()
inps = cmdLineParse()
projectName = inps.projectName
DATE = inps.date
scratchDir = os.getenv('SCRATCHDIR')
templateDir = os.getenv('TEMPLATEDIR')
slcDir = scratchDir + '/' + projectName + '/SLC'
projDir = scratchDir + '/' + projectName
ERS1_Orb_Dir = scratchDir + '/' + projectName + '/ERS1_Orb'
ERS2_Orb_Dir = scratchDir + '/' + projectName + '/ERS2_Orb'
if not os.path.isdir(ERS1_Orb_Dir):
call_str = 'mkdir ' + ERS1_Orb_Dir
os.system(call_str)
if not os.path.isdir(ERS2_Orb_Dir):
call_str = 'mkdir ' + ERS2_Orb_Dir
os.system(call_str)
ERS1_Orb_list = ERS1_Orb_Dir + '/ERS1_Orb_list'
ERS2_Orb_list = ERS2_Orb_Dir + '/ERS2_Orb_list'
os.chdir(ERS1_Orb_Dir)
if not os.path.isfile(ERS1_Orb_list):
Url = 'ftp://dutlru2.lr.tudelft.nl/pub/orbits/ODR.ERS-1/dgm-e04/arclist'
call_str = 'wget ' + Url + ' -O ERS1_Orb_list'
os.system(call_str)
call_str = 'cp ERS1_Orb_list arclist'
os.system(call_str)
os.chdir(ERS2_Orb_Dir)
if not os.path.isfile(ERS2_Orb_list):
Url = 'ftp://dutlru2.lr.tudelft.nl/pub/orbits/ODR.ERS-2/dgm-e04/arclist'
call_str = 'wget ' + Url + ' -O ERS2_Orb_list'
os.system(call_str)
call_str = 'cp ERS2_Orb_list arclist'
os.system(call_str)
if len(DATE)==8:
DATE6 = DATE[2:8]
else:
DATE6 = DATE
slcDir1 = slcDir + '/' + DATE6
slcpar = slcDir1 + '/' + DATE6 + '.slc.par'
Title = UseGamma(slcpar, 'read', 'title:')
if 'E1' in Title:
Flag = 'ERS1'
Url = 'ftp://dutlru2.lr.tudelft.nl/pub/orbits/ODR.ERS-1/dgm-e04/'
List = ERS1_Orb_list
Dir = ERS1_Orb_Dir
elif 'E2' in Title:
Flag = 'ERS2'
Url = 'ftp://dutlru2.lr.tudelft.nl/pub/orbits/ODR.ERS-2/dgm-e04/'
List = ERS2_Orb_list
Dir = ERS2_Orb_Dir
else:
print('The SAR data is invalid.')
sys.exit(1)
if len(DATE)==6:
A0 = int(DATE[0:2])
if A0 < 50:
DATE = '20' + DATE
else:
DATA = '19' + DATE
YYMM = DATE6[0:2] + DATE6[2:4]
call_str = 'grep ' + YYMM + ' ' + List + ' > list0'
os.system(call_str)
call_str = "awk '{print $12}' list0 > start_end"
os.system(call_str)
call_str = "awk '{print $1}' list0 > vec_num"
os.system(call_str)
AA= np.loadtxt('start_end',dtype=np.str)
Na = AA.size
print(AA)
A_num= np.loadtxt('vec_num',dtype=np.str)
Na_num = A_num.size
for i in range(Na-1):
A0 = AA[i]
A1 = AA[i+1]
print(DATE6)
print(A0)
print(A1)
if int(DATE6)==int(A0):
m = i
elif int(DATE6)==int(A1):
m = i+1
elif int(A0) < int(DATE6) < int(A1):
m = i
FF = A_num[int(m)]
SS = Url + 'ODR.' + FF
print(SS)
call_str = 'wget -q --no-check-certificate ' + SS + ' -P ' + Dir
os.system(call_str)
print("Download precise DEFT orbital data for %s is done." % DATE)
sys.exit(1)
if __name__ == '__main__':
main(sys.argv[:])
@@ -0,0 +1,132 @@
#! /usr/bin/env python
#################################################################
### This program is part of PyINT v1.0 ###
### Copy Right (c): 2017, Yunmeng Cao ###
### Author: Yunmeng Cao ###
### Email : ymcmrs@gmail.com ###
### Univ. : Central South University & University of Miami ###
#################################################################
import numpy as np
import os
import sys
import subprocess
import getopt
import time
import glob
import argparse
import linecache
def StrNum(S):
S = str(S)
if len(S)==1:
S='0' +S
return S
def UseGamma(inFile, task, keyword):
if task == "read":
f = open(inFile, "r")
while 1:
line = f.readline()
if not line: break
if line.count(keyword) == 1:
strtemp = line.split(":")
value = strtemp[1].strip()
return value
print("Keyword " + keyword + " doesn't exist in " + inFile)
f.close()
#########################################################################
INTRODUCTION = '''
#############################################################################
Copy Right(c): 2017-2019, Yunmeng Cao @PyINT v1.0
Precise ERS orbit data from Delft (http://www.deos.tudelft.nl/).
Correct the orbit parameters using DELFT_vec2
'''
EXAMPLE = '''
Usage:
ERS_orb_cor.py projectName Date
Examples:
ERS_orb_cor.py AqabaERSA 960101
##############################################################################
'''
def cmdLineParse():
parser = argparse.ArgumentParser(description='Download (and correct) precise ERS orbit data.',\
formatter_class=argparse.RawTextHelpFormatter,\
epilog=INTRODUCTION+'\n'+EXAMPLE)
parser.add_argument('projectName',help='project name')
parser.add_argument('date',help='date of the ERS data')
inps = parser.parse_args()
return inps
################################################################################
def main(argv):
total = time.time()
inps = cmdLineParse()
projectName = inps.projectName
DATE = inps.date
scratchDir = os.getenv('SCRATCHDIR')
templateDir = os.getenv('TEMPLATEDIR')
Ers1OrbDir = os.getenv('ERS1ORBDIR')
Ers2OrbDir = os.getenv('ERS2ORBDIR')
slcDir = scratchDir + '/' + projectName + '/SLC'
projDir = scratchDir + '/' + projectName
if len(DATE)==8:
DATE6 = DATE[2:8]
else:
DATE6 = DATE
slcDir1 = slcDir + '/' + DATE6
slcpar = slcDir1 + '/' + DATE6 + '.slc.par'
Title = UseGamma(slcpar, 'read', 'title:')
if 'E1' in Title:
Flag = 'ERS1'
#Url = 'ftp://dutlru2.lr.tudelft.nl/pub/orbits/ODR.ERS-1/dgm-e04/'
#List = ERS1_Orb_list
Dir = Ers1OrbDir
elif 'E2' in Title:
Flag = 'ERS2'
#Url = 'ftp://dutlru2.lr.tudelft.nl/pub/orbits/ODR.ERS-2/dgm-e04/'
#List = ERS2_Orb_list
Dir = Ers2OrbDir
else:
print('The SAR data is invalid.')
sys.exit(1)
call_str = 'DELFT_vec2 ' + slcpar + ' ' + Dir + ' 30'
os.system(call_str)
print("Using DEFT orbital data for %s is done." % DATE)
sys.exit(1)
if __name__ == '__main__':
main(sys.argv[:])
@@ -0,0 +1,126 @@
#! /usr/bin/env python
#################################################################
### This program is part of PyINT v1.0 ###
### Copy Right (c): 2017, Yunmeng Cao ###
### Author: Yunmeng Cao ###
### Email : ymcmrs@gmail.com ###
### Univ. : Central South University & University of Miami ###
#################################################################
import numpy as np
import os
import sys
import subprocess
import getopt
import time
import glob
import argparse
import linecache
def StrNum(S):
S = str(S)
if len(S)==1:
S='0' +S
return S
def UseGamma(inFile, task, keyword):
if task == "read":
f = open(inFile, "r")
while 1:
line = f.readline()
if not line: break
if line.count(keyword) == 1:
strtemp = line.split(":")
value = strtemp[1].strip()
return value
print("Keyword " + keyword + " doesn't exist in " + inFile)
f.close()
def is_number(s):
try:
int(s)
return True
except ValueError:
return False
#########################################################################
INTRODUCTION = '''
#############################################################################
Copy Right(c): 2017-2019, Yunmeng Cao @PyINT v1.0
Precise ERS orbit data from Delft (http://www.deos.tudelft.nl/).
Correct the orbit parameters using DELFT_vec2
'''
EXAMPLE = '''
Usage:
ERS_orb_cor_all.py projectName
Examples:
ERS_orb_cor_all.py AqabaERSA
##############################################################################
'''
def cmdLineParse():
parser = argparse.ArgumentParser(description='Download (and correct) precise ERS orbit data.',\
formatter_class=argparse.RawTextHelpFormatter,\
epilog=INTRODUCTION+'\n'+EXAMPLE)
parser.add_argument('projectName',help='project name')
inps = parser.parse_args()
return inps
################################################################################
def main(argv):
total = time.time()
inps = cmdLineParse()
projectName = inps.projectName
scratchDir = os.getenv('SCRATCHDIR')
templateDir = os.getenv('TEMPLATEDIR')
slcDir = scratchDir + '/' + projectName + '/SLC'
ListSLC = os.listdir(slcDir)
Datelist = []
SLCfile = []
SLCParfile = []
for kk in range(len(ListSLC)):
if ( is_number(ListSLC[kk]) and len(ListSLC[kk])==6 ): # if SAR date number is 8, 6 should change to 8.
DD=ListSLC[kk]
Year=int(DD[0:2])
Month = int(DD[2:4])
Day = int(DD[4:6])
Datelist.append(ListSLC[kk])
N = len(Datelist)
for i in range(N):
call_str = 'ERS_orb_cor.py ' + projectName + ' ' + Datelist[i]
print(call_str)
os.system(call_str)
print("Using DEFT orbital data for project %s is done." % projectName)
sys.exit(1)
if __name__ == '__main__':
main(sys.argv[:])
@@ -0,0 +1,118 @@
#! /usr/bin/env python
#################################################################
### This program is part of PyINT v1.0 ###
### Copy Right (c): 2017, Yunmeng Cao ###
### Author: Yunmeng Cao ###
### Email : ymcmrs@gmail.com ###
### Univ. : Central South University & University of Miami ###
#################################################################
import numpy as np
import os
import sys
import subprocess
import getopt
import time
import glob
import argparse
import linecache
def StrNum(S):
S = str(S)
if len(S)==1:
S='0' +S
return S
def UseGamma(inFile, task, keyword):
if task == "read":
f = open(inFile, "r")
while 1:
line = f.readline()
if not line: break
if line.count(keyword) == 1:
strtemp = line.split(":")
value = strtemp[1].strip()
return value
print("Keyword " + keyword + " doesn't exist in " + inFile)
f.close()
#########################################################################
INTRODUCTION = '''
#############################################################################
Copy Right(c): 2017-2019, Yunmeng Cao @PyINT v1.0
Precise ERS orbit data from Delft (http://www.deos.tudelft.nl/).
Correct the orbit parameters using DELFT_vec2
'''
EXAMPLE = '''
Usage:
ERS_orb_cor_par.py SLC_par
Examples:
ERS_orb_cor_par.py 960101.slc.par
##############################################################################
'''
def cmdLineParse():
parser = argparse.ArgumentParser(description='Download (and correct) precise ERS orbit data.',\
formatter_class=argparse.RawTextHelpFormatter,\
epilog=INTRODUCTION+'\n'+EXAMPLE)
parser.add_argument('slc_par',help='slc par file')
inps = parser.parse_args()
return inps
################################################################################
def main(argv):
total = time.time()
inps = cmdLineParse()
slcpar = inps.slc_par
Ers1OrbDir = os.getenv('ERS1ORBDIR')
Ers2OrbDir = os.getenv('ERS2ORBDIR')
Title = UseGamma(slcpar, 'read', 'title:')
if 'E1' in Title:
Flag = 'ERS1'
#Url = 'ftp://dutlru2.lr.tudelft.nl/pub/orbits/ODR.ERS-1/dgm-e04/'
#List = ERS1_Orb_list
Dir = Ers1OrbDir
elif 'E2' in Title:
Flag = 'ERS2'
#Url = 'ftp://dutlru2.lr.tudelft.nl/pub/orbits/ODR.ERS-2/dgm-e04/'
#List = ERS2_Orb_list
Dir = Ers2OrbDir
else:
print('The SAR data is invalid.')
sys.exit(1)
call_str = 'DELFT_vec2 ' + slcpar + ' ' + Dir
os.system(call_str)
print("Using DEFT orbital data for %s is done." % slcpar)
sys.exit(1)
if __name__ == '__main__':
main(sys.argv[:])
@@ -0,0 +1,131 @@
#!/bin/csh -f
# $Id$
#GACOS Correction
#Erik Rivas, Oct 18 2021
#
if ($#argv != 5) then
echo ""
echo "Usage: GACOS.csh list_interferograms full_path_to_GACOS_data full_path_topo reference_point incidence_angle"
echo "Script needs to be run inside the intf_all folder"
echo "Performs gacos correction"
echo ""
echo "list_interferograms: list of folders inside the intf_all folder containing the phases and coherence grids"
echo ""
echo "full_path_to_GACOS_data"
echo "Example: /home/erikr/gacos/"
echo ""
echo "full_path_topo"
echo "Example: /home/erikr/project/topo/"
echo ""
echo "the topo folder needs to have: dem.grd, master.PRM, and the correspondant .LED file"
echo ""
echo "list_interferograms: list of folders with interferograms created"
echo ""
echo "Reference point in lon lat coordinates (text file)"
echo ""
echo "Indicence angle in degrees from SAT_look (float/integer)"
echo ""
echo "Outputs: phasefilt.grd files corrected and added as additional products in each interferogram folder. These outputs should be used for the unwrap processing"
exit 1
endif
set list = $1
set GACOS_dir = $2
set topo_dir = $3
set reference_point = $4
set incidence = $5
#Checking inputs
if !(-e $list) then
echo "$list seems not to exist"
exit 1
endif
if !(-d $GACOS_dir) then
echo "$GACOS_dir seems not to exist"
exit 1
endif
if !(-d $topo_dir) then
echo "$topo_dir seems not to exist"
exit 1
endif
if !(-f $reference_point) then
echo "Reference point file: $reference_point seems not to exist. Provide a text file with lon lat values"
exit 1
endif
#PROJECT POINT FROM LON-LAT TO RADAR COORDINATES
set ref_llh = $topo_dir"ref.llh"
set out_ratll = $topo_dir"out.ratll"
set reference_point_ra = $topo_dir"ref_point.ra"
if (-f $ref_llh) then
echo "Removing old $ref_llh"
rm $ref_llh
endif
if (-f $out_ratll) then
echo "Removing old $out_ratll"
rm $out_ratll
endif
if (-f $reference_point_ra) then
echo "Removing old $reference_point_ra"
rm $reference_point_ra
endif
gmt grdtrack $reference_point -G$topo_dir"dem.grd" >> $ref_llh
ln -s $topo_dir*.LED .
SAT_llt2rat $topo_dir"master.PRM" 0 < $topo_dir"ref.llh" > $out_ratll
rm *.LED
cat $out_ratll |awk '{print $1, $2}' > $reference_point_ra
set dem_grd = $topo_dir"dem.grd"
#----------------------------------------------#
#FOR LOOP OVER LIST OF INTERFEROGRAMS
foreach dir (`awk '{print $1}' $list`)
if !(-d $dir) then
echo "$dir directory seems not to exist"
exit 1
endif
cd $dir
#Check if there are only two SLC files (not sure if this step is neccessary)
if (`ls *.SLC|wc -l` != "2") then
echo "the number of SLC files is inconsistent"
endif
#ls sorts content alphanumeric, therefore it is assume the first as the master on the list
set fst_date = `ls *.SLC|sed -n '1p'|awk '{print substr($1,4,8)}'`
set scd_date = `ls *.SLC|sed -n '2p'|awk '{print substr($1,4,8)}'`
#Save directory of current intf
set intf_dir = `pwd`
cd $GACOS_dir
#Check if the GACOS files are in the folder
if (-f $fst_date".ztd" && -f $fst_date".ztd.rsc" && -f $scd_date".ztd" && -f $scd_date".ztd.rsc") then
set first_ztd = $GACOS_dir$fst_date".ztd"
set first_rsc = $GACOS_dir$fst_date".ztd.rsc"
set second_ztd = $GACOS_dir$scd_date".ztd"
set second_rsc = $GACOS_dir$scd_date".ztd.rsc"
#GACOS Correction
cd $intf_dir
#Link trans.dat to each folder. Neccesary to project ztd grids to radar coordinates
ln -s $topo_dir"trans.dat"
operation.csh $first_ztd $first_rsc $second_ztd $second_rsc $reference_point_ra $incidence $dem_grd
rm trans.dat
else
echo "GACOS files do not exist / Wrong directory"
exit 1
endif
cd ..
end
echo "GACOS correction done"
@@ -0,0 +1,145 @@
#! /usr/bin/env python
#################################################################
### This program is part of PyINT v1.0 ###
### Copy Right (c): 2017, Yunmeng Cao ###
### Author: Yunmeng Cao ###
### Email : ymcmrs@gmail.com ###
### Univ. : Central South University & University of Miami ###
#################################################################
import os
import sys
import glob
import time
import argparse
import h5py
import numpy as np
def check_variable_name(path):
s=path.split("/")[0]
if len(s)>0 and s[0]=="$":
p0=os.getenv(s[1:])
path=path.replace(path.split("/")[0],p0)
return path
def read_template(File, delimiter='='):
'''Reads the template file into a python dictionary structure.
Input : string, full path to the template file
Output: dictionary, pysar template content
Example:
tmpl = read_template(KyushuT424F610_640AlosA.template)
tmpl = read_template(R1_54014_ST5_L0_F898.000.pi, ':')
'''
template_dict = {}
for line in open(File):
line = line.strip()
c = [i.strip() for i in line.split(delimiter, 1)] #split on the 1st occurrence of delimiter
if len(c) < 2 or line.startswith('%') or line.startswith('#'):
next #ignore commented lines or those without variables
else:
atrName = c[0]
atrValue = str.replace(c[1],'\n','').split("#")[0].strip()
atrValue = check_variable_name(atrValue)
template_dict[atrName] = atrValue
return template_dict
def UseGamma(inFile, task, keyword):
if task == "read":
f = open(inFile, "r")
while 1:
line = f.readline()
if not line: break
if line.count(keyword) == 1:
strtemp = line.split(":")
value = strtemp[1].strip()
return value
print("Keyword " + keyword + " doesn't exist in " + inFile)
f.close()
def UseGamma2(inFile, task, keyword):
if task == "read":
f = open(inFile, "r")
while 1:
line = f.readline()
if not line: break
if line.count(keyword) == 1:
strtemp = line.split(":")
value = strtemp[2].strip()
return value
print("Keyword " + keyword + " doesn't exist in " + inFile)
f.close()
def usage():
print('''
******************************************************************************************************
Get co-registration standard deviation of SLCs for one project
usage:
GenerateRSC_Gamma.py projectName
e.g. Get_off_std.py GalapagosT061EnvA
*******************************************************************************************************
''')
def main(argv):
if len(sys.argv)==2:
if argv[0] in ['-h','--help']: usage(); sys.exit(1)
else: projectName=sys.argv[1]
else:
usage();sys.exit(1)
scratchDir = os.getenv('SCRATCHDIR')
OFFDir = scratchDir + '/' + projectName + '/RSLC'
OFFSTR = OFFDir + '/*.off_std'
OFFFile = glob.glob(OFFSTR)
STD_TXT ='COREG_STD_ALL'
os.chdir(OFFDir)
if os.path.isfile(STD_TXT):
os.remove(STD_TXT)
for ff in OFFFile:
OFF_STD = ff
NM = os.path.basename(ff).split('.')[0]
RR = UseGamma(OFF_STD,'read','final range offset poly. coeff.:')
cor_rg = RR.split(' ')[0]
AA = UseGamma(OFF_STD,'read','final azimuth offset poly. coeff.:')
cor_az = AA.split(' ')[0]
STDRR = UseGamma(OFF_STD,'read','final model fit std. dev. (samples) range:')
std_rg=STDRR.split(' ')[0]
std_az = UseGamma2(OFF_STD,'read','final model fit std. dev. (samples) range:')
STR = NM + ' ' + cor_rg + ' ' + cor_az + ' ' + std_rg + ' ' + std_az
call_str ='echo ' + STR + ' >> ' + STD_TXT
os.system(call_str)
sys.exit(1)
if __name__ == '__main__':
main(sys.argv[1:])
@@ -0,0 +1,5 @@
*.swp
bin/
*.tif
*.pyc
__pycache__/
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@@ -0,0 +1,582 @@
#!/usr/bin/env python3
import os
import re
from datetime import datetime, timedelta
import numpy as np
import rasterio
from bin.multilook_w import multilook_w
from bin.multilook import multilook
import configparser
import sys
import warnings
import pickle
import glob
warnings.filterwarnings("ignore", category=DeprecationWarning)
#######################################################################
HELP_TEXT = """
PhaseBias_01_Read_Data.py
This script automates the process of downloading GeoTIFF files for wrapped interferograms and coherence images.
The files can be retrieved either from the COMET-LiCS web portal or from a root path specified in the configuration file.
Assumptions:
- Interferograms are organized in folders named as `yyyymmdd_yyyymmdd` (e.g., `20230101_20230107`).
Files Downloaded:
1. `yyyymmdd_yyyymmdd.geo.diff_pha.tif`:
- Contains the wrapped phase image in radians.
- Values range from -3.14 to 3.14.
2. `yyyymmdd_yyyymmdd.geo.cc.tif`:
- Contains the coherence image of the interferometric pair.
- Values range from 0 to 255, where:
- 0 represents the lowest coherence.
- 255 represents the highest coherence.
Outputs:
1. `All_ifgs_start_end` (Pickle file, saved as `.pkl`):
- A dictionary containing all interferograms available between the specified start and end dates.
2. `All_coh_start_end` (Pickle file, saved as `.pkl`):
- A dictionary containing all coherence data available between the specified start and end dates.
Storage Information:
- All output files are saved in the directory `Data/` under the `output_path` defined in the configuration file.
Additional Output:
- A summary report is generated that includes:
- The number of available interferograms for each temporal baseline.
- The number of missing interferograms.
"""
if "--help" in sys.argv:
print(HELP_TEXT)
sys.exit(0)
###################
# Config file path
config_file = "config.txt"
# Check if config file exists
if not os.path.exists(config_file):
raise FileNotFoundError(
f"Error: The configuration file '{config_file}' was not found in the script's directory."
)
# Initialize the configparser
config = configparser.ConfigParser()
# Read the config.txt file
config.read(config_file)
# Define required parameters
required_parameters = [
"root_path",
"frame",
"start",
"end",
"interval",
"nlook",
"LiCSAR_data",
]
# Initialize a dictionary to store parameters
parameters = {}
# Attempt to retrieve each parameter and catch errors
try:
parameters["root_path"] = config.get("DEFAULT", "root_path")
parameters["output_path"] = config.get("DEFAULT", "output_path")
parameters["frame"] = config.get("DEFAULT", "frame")
parameters["start"] = config.get("DEFAULT", "start")
parameters["end"] = config.get("DEFAULT", "end")
parameters["interval"] = config.getint("DEFAULT", "interval")
parameters["nlook"] = config.getint(
"DEFAULT", "nlook") # Assuming 'nlook' should be an integer
parameters["LiCSAR_data"] = config.get("DEFAULT", "LiCSAR_data")
except configparser.NoOptionError as e:
# Error message if a required parameter is missing
missing_param = str(e).split(": ")[1]
raise ValueError(
f"Error: Required parameter '{missing_param}' is missing in '{config_file}'. Please check the file contents."
)
except configparser.Error as e:
# General error for any configparser-related issues
raise ValueError(f"Error while reading '{config_file}': {e}")
# Assign to individual variables for easy access
root_path = parameters["root_path"]
output_path = parameters["output_path"]
frame = parameters["frame"]
start = parameters["start"]
end = parameters["end"]
interval = parameters["interval"]
nlook = parameters["nlook"]
LiCSAR_data = parameters["LiCSAR_data"]
# hardcoded parameters, not included in the config file
landmask = 1
filtered_ifgs = "yes"
min_baseline = 5
max_baseline = 366
# Print the values to confirm they're being read correctly
print("Root Path:", root_path)
print("output Path:", output_path)
print("Frame:", frame)
print("Start Date:", start)
print("End Date:", end)
print("Interval:", interval)
print("nlook:", nlook)
print("LiCSAR_data", LiCSAR_data)
################
# all_ifgs = read_ifgs(frame, start, end, min_baseline, max_baseline, landmask, nlook, interval, LiCSAR_data, filtered_ifgs)
def read_ifgs(
start,
end,
min_baseline,
max_baseline,
landmask,
nlook,
interval,
LiCSAR_data,
filtered_ifgs,
):
start_date = datetime.strptime(start, "%Y%m%d")
end_date = datetime.strptime(end, "%Y%m%d")
# Check if the file ends with "geo.diff_pha.tif"
# if filename.endswith("geo.diff_unfiltered_pha.tif"): # if unfiltered data are used
if filtered_ifgs == "yes": # yes for the filtered ifgs, no for the unfiltered ifgs
req_file_name = "geo.diff_pha.tif"
else:
req_file_name = "geo.diff_unfiltered_pha.tif"
############ reading
if LiCSAR_data == "yes":
track = frame[0:3] # extracting track number from frame id
if track[0] == "0":
track = track[1:3]
if track[0] == "0":
track = track[1:2]
root_directory = f"/gws/nopw/j04/nceo_geohazards_vol1/public/LiCSAR_products/{track}/{frame}/interferograms/"
else:
root_directory = os.path.join(root_path, "interferograms") # Use os.path.join for consistent path construction
#root_directory = os.path.join(root_path, "")
##### Count total files matching the criteria for accurate progress calculation
print(f"Reading data from the path: {root_directory}")
total_files = sum(1 for dirpath, _, filenames in os.walk(root_directory)
for filename in filenames
if filename.endswith(req_file_name))
processed_files = 0
print("Reading wrapped interferograms: [", end="", flush=True)
#####
# Initialize an empty dictionary to store the arrays for each category
category_arrays = {}
last_date = {}
n = 0
if landmask is not None:
if LiCSAR_data == "yes":
landmask_path = f"/gws/nopw/j04/nceo_geohazards_vol1/public/LiCSAR_products/{track}/{frame}/metadata/{frame}.geo.landmask.tif"
else:
# Use glob to find the file ending with ".geo.landmask.tif" in the metadata directory
metadata_dir = os.path.join(root_path, "metadata")
landmask_files = glob.glob(
os.path.join(metadata_dir, "*.geo.landmask.tif"))
if landmask_files:
landmask_path = landmask_files[0] # Take the first match
else:
raise FileNotFoundError(
"No file ending with '.geo.landmask.tif' found in the metadata directory."
)
# Load the landmask file
with rasterio.open(landmask_path) as src:
array_landmask = src.read(1)
n = 1
# Traverse the root directory and its subdirectories
for dirpath, dirnames, filenames in os.walk(root_directory):
dirnames.sort(
) # This ensures dirnames are processed in alphabetical order
# Iterate through the files in the current directory
for filename in filenames:
# Check if the file ends with "geo.diff_pha.tif"
# if filename.endswith("geo.diff_unfiltered_pha.tif"): # if unfiltered data are used
if (filtered_ifgs == "yes"
): # yes for the filtered ifgs, no for the unfiltered ifgs
req_file_name = "geo.diff_pha.tif"
else:
req_file_name = "geo.diff_unfiltered_pha.tif"
if filename.endswith(req_file_name):
file_path = os.path.join(dirpath, filename)
#### for printing into the console
processed_files += 1
percentage = (processed_files / total_files) * 100
# Clear previous percentage and print updated one
sys.stdout.write(
"\rReading wrapped phases: [{:<50}] {}%".format(
"=" * int(percentage // 2), int(percentage)))
sys.stdout.flush()
#####
# Extract the dates from the file name
match = re.search(r"(\d+)_(\d+)", filename)
if match:
date1 = match.group(1)
date2 = match.group(2)
# Convert the dates to datetime objects
date1_obj = datetime.strptime(date1, "%Y%m%d")
date2_obj = datetime.strptime(date2, "%Y%m%d")
# Check if the dates fall within the specified range
category = (date2_obj - date1_obj).days
if (start_date <= date1_obj <= end_date
and start_date <= date2_obj <= end_date
and category < max_baseline
and category > min_baseline):
if (
n == 1
): # finding the first and last acquisiton in the time-series
first_acq = date1_obj
else:
last_acq = date2_obj
n = n + 1
# Calculate the difference in days between the two dates
# Open the TIFF file
try:
with rasterio.open(file_path) as src:
array_data = src.read(1).astype(np.float32)
except Exception as e:
print(f"\u26a0\ufe0f Error reading {file_path}: {e}. Appending None instead.")
array_data = None
#if array_data is not None:
array_data[array_data == 0] = np.nan ## converting the zerso values in wrapped phases into nan. This is helpful when calculating loop closures
#array_data[np.abs(array_data) < 1e-8] = np.nan # as after filter i observed low vlaues outside the frame. I also wanted to nulify them. so used this insteadof above
if landmask != None: #and array_data is not None:
array_data[array_landmask != 1] = np.nan
if (
nlook != None and nlook != 1 #and array_data is not None
): # incase of unwrap data because they are already multilooked to 10 we don't multilook them here
array_data = multilook_w(array_data, nlook)
if category not in last_date:
last_date[category] = date1_obj
# if (date1_obj - date2_obj) > interval
# appending None to the category_arrays where there are missing ifgs in the middle of time-series
diff_ifgs = (
date1_obj - last_date[category]
).days # /category #difference between the first epochs of two consecutive ifg
if diff_ifgs > interval:
n_no_acq = int(diff_ifgs / interval -
1) ## number of missing ifgs
for i in range(
n_no_acq
): # the number of none depends on the number of missing ifgs
# Append the none to the existing array
category_arrays[category].append(None)
last_date[category] = date1_obj
# Check if the category is already in the dictionary
if category in category_arrays:
# If the category already exists, append the array to the existing array
category_arrays[category].append(array_data)
else:
# If the category doesn't exist, create a new list with the array
category_arrays[category] = [array_data]
# appending None to the category_arrays where there are missing ifgs in the end of time-series
for category in sorted(category_arrays):
while (last_date[category] + timedelta(category)) < last_acq:
category_arrays[category].append(None)
last_date[category] = last_date[category] + timedelta(interval)
# appending None to the category_arrays where there are missing ifgs in the begining of time-series
# max number of expected 6-day(i.e. interval) interferograms in the full time-series
max_ifg_number = abs(int((first_acq - last_acq).days / interval))
# all the categories in the data e.g. 6, 12, 18 etc
cat = []
for category in category_arrays:
cat.append(category)
for i in range(interval, max(cat)+1, interval):
if i in cat:
while len(category_arrays[i]) < (max_ifg_number + 1 - i/interval):
category_arrays[i].insert( 0, None)
print("\nFinished reading all interferograms.")
return category_arrays
###########################################################################################################################
##########################################################################################################################
def read_coh(start, end, min_baseline, max_baseline, landmask, nlook, interval,
LiCSAR_data):
start_date = datetime.strptime(start, "%Y%m%d")
end_date = datetime.strptime(end, "%Y%m%d")
############ reading
if LiCSAR_data == "yes":
track = frame[0:3]
if track[0] == "0":
track = track[1:3]
if track[0] == "0":
track = track[1:2]
root_directory = f"/gws/nopw/j04/nceo_geohazards_vol1/public/LiCSAR_products/{track}/{frame}/interferograms/"
else:
root_directory = os.path.join(
root_path, "interferograms"
) # Use os.path.join for consistent path construction
req_file_name = "geo.cc.tif"
##### Count total files matching the criteria for accurate progress calculation
total_files = sum(1 for dirpath, _, filenames in os.walk(root_directory)
for filename in filenames
if filename.endswith(req_file_name))
processed_files = 0
print("Reading coherence data: [", end="", flush=True)
#####
# Initialize an empty dictionary to store the arrays for each category
category_arrays = {}
last_date = {}
n = 0
if landmask is not None:
if LiCSAR_data == "yes":
landmask_path = f"/gws/nopw/j04/nceo_geohazards_vol1/public/LiCSAR_products/{track}/{frame}/metadata/{frame}.geo.landmask.tif"
else:
# Use glob to find the file ending with ".geo.landmask.tif" in the metadata directory
metadata_dir = os.path.join(root_path, "metadata")
landmask_files = glob.glob(
os.path.join(metadata_dir, "*.geo.landmask.tif"))
if landmask_files:
landmask_path = landmask_files[0] # Take the first match
else:
raise FileNotFoundError(
"No file ending with '.geo.landmask.tif' found in the metadata directory."
)
# Load the landmask file
with rasterio.open(landmask_path) as src:
array_landmask = src.read(1)
n = 1
# Traverse the root directory and its subdirectories
for dirpath, dirnames, filenames in os.walk(root_directory):
# Iterate through the files in the current directory
for filename in filenames:
# Check if the file ends with "geo.cc.tif"
if filename.endswith(req_file_name):
file_path = os.path.join(dirpath, filename)
#### for printing into the console
processed_files += 1
percentage = (processed_files / total_files) * 100
# Clear previous percentage and print updated one
sys.stdout.write(
"\rReading coherence data: [{:<50}] {}%".format(
"=" * int(percentage // 2), int(percentage)))
sys.stdout.flush()
#####
# Extract the dates from the file name
match = re.search(r"(\d+)_(\d+)", filename)
if match:
date1 = match.group(1)
date2 = match.group(2)
# Convert the dates to datetime objects
date1_obj = datetime.strptime(date1, "%Y%m%d")
date2_obj = datetime.strptime(date2, "%Y%m%d")
# Check if the dates fall within the specified range
category = (date2_obj - date1_obj).days
if (start_date <= date1_obj <= end_date
and start_date <= date2_obj <= end_date
and category < max_baseline
and category > min_baseline):
if (
n == 1
): # finding the first and last acquisiton in the time-series
first_acq = date1_obj
else:
last_acq = date2_obj
n = n + 1
# Calculate the difference in days between the two dates
# Open the TIFF file
try:
with rasterio.open(file_path) as src:
array_data = src.read(1).astype(np.float32)
except Exception as e:
print(f"\u26a0\ufe0f Error reading {file_path}: {e}. Appending None instead.")
array_data = None
if landmask != 0:
array_data[array_landmask != 1] = np.nan
if (
nlook != None and nlook != 1
): # incase of unwrap data because they are already multilooked to 10 we don't multilook them here
array_data = multilook(array_data, nlook)
if category not in last_date:
last_date[category] = date1_obj
# if (date1_obj - date2_obj) > interval
# appending None to the category_arrays where there are missing ifgs in the middle of time-series
diff_ifgs = (
date1_obj - last_date[category]
).days # /category #difference between the first epochs of two consecutive ifg
if diff_ifgs > interval:
n_no_acq = int(diff_ifgs / interval -
1) ## number of missing ifgs
for i in range(
n_no_acq
): # the number of none depends on the number of missing ifgs
# Append the none to the existing array
category_arrays[category].append(None)
last_date[category] = date1_obj
# Check if the category is already in the dictionary
if category in category_arrays:
# If the category already exists, append the array to the existing array
category_arrays[category].append(array_data)
else:
# If the category doesn't exist, create a new list with the array
category_arrays[category] = [array_data]
# appending None to the category_arrays where there are missing ifgs in the end of time-series
for category in sorted(category_arrays):
while (last_date[category] + timedelta(category)) < last_acq:
category_arrays[category].append(None)
last_date[category] = last_date[category] + timedelta(interval)
# appending None to the category_arrays where there are missing ifgs in the begining of time-series
# max number of expected 6-day(i.e. interval) interferograms in the full time-series
max_ifg_number = abs(int((first_acq - last_acq).days / interval))
# all the categories in the data e.g. 6, 12, 18 etc
cat = []
for category in category_arrays:
cat.append(category)
for i in range(interval, max(cat)+1, interval):
if i in cat:
while len(category_arrays[i]) < (max_ifg_number + 1 - i/interval):
category_arrays[i].insert(0, None)
print("\nFinished reading all coherence data.")
return category_arrays
##########################################################################################################################
##########################################################################################################################
all_ifgs = read_ifgs(
start,
end,
min_baseline,
max_baseline,
landmask,
nlook,
interval,
LiCSAR_data,
filtered_ifgs,
)
# Define the directory path
directory_path = os.path.join(output_path, "Data")
# Create the directory if it doesn't exist
os.makedirs(directory_path, exist_ok=True)
# Define the file path
#file_path = os.path.join(directory_path, f"_all_ifgs_{start}_{end}")
# Remove all files inside the directory
if os.path.exists(directory_path):
files = glob.glob(os.path.join(directory_path, "*"))
for file in files:
os.remove(file)
# for writing the all_loops
file_path = output_path + "/Data/" + "All_ifgs_" + start + "_" + end + ".pkl"
with open(file_path, "wb") as file: # for writting a dictionary to a file
pickle.dump(all_ifgs, file)
################################################
# After processing all interferograms, generate the report
print("\nReport on the number of IFGs and missing IFGs per category:")
for category in sorted(all_ifgs):
num_ifgs = sum(1 for item in all_ifgs[category]
if item is not None) # Count valid IFGs
num_missing_ifgs = sum(1 for item in all_ifgs[category]
if item is None) # Count missing IFGs
print(
f"{category}-days: Number of IFGs: {num_ifgs} Number of missing IFGs: {num_missing_ifgs}"
)
################################################################
import gc
del all_ifgs
gc.collect()
all_coh = read_coh(start, end, min_baseline, max_baseline, landmask, nlook,
interval, LiCSAR_data)
## for writting the all_coh
file_path = output_path + "/Data/" + "All_coh_" + start + "_" + end + ".pkl"
with open(file_path, "wb") as file: # for writting a dictionary to a file
pickle.dump(all_coh, file)
@@ -0,0 +1,323 @@
#!/usr/bin/env python3
import numpy as np
import pickle
import glob
import configparser
import os
import sys
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
################################################################################################
HELP_TEXT = """
PhaseBias_02_Loop_Closures.py
This script calculates loop closures (Δφ) using the interferograms imported in the first step.
Definition of Loop Closures:
Loop closures, Δφ, are calculated for the epochs between `i` and `k`, and are defined as:
Δφ_(i,k) = |φ_(i,k) - ∑_(t=i)^k φ_(t,t+1)|_2π
Where:
- φ_(i,j): Represents the phase difference for a pixel in the interferogram formed between epochs `i` and `j`.
- |.|_2π: Indicates that the result is wrapped modulo 2π (i.e., values range from -π to π).
Key Information:
- Nonzero closure phase is a by-product of spatial filtering/multilooking and is primarily associated with changes in the scattering and electrical properties of the ground surface.
- The calculated loop closures are based on the minimum temporal-baseline interferograms defined in the configuration file (parameter: `interval`) and are referred to as base interferograms. These may represent:
- 12- and 6-day closures (or 24- and 12-day closures), Δφ_(i,i+2)
- 18- and 6-day closures (or 36- and 12-day closures), Δφ_(i,i+3)
The distinction depends on whether the base interferograms are 6-day or 12-day intervals.
Outputs:
- The calculated loop closures are stored as a dictionary in a file named:
`All_loops_start_end.pkl`
- The output is saved in the directory `Data/` under the `output_path` defined in the configuration file.
Loop Closure Report:
At the end of the script, a loop closure report is displayed. This report includes:
- The number of generated and missing loop closures for short-interval closures, such as 12-6 and 18-6.
- The number of generated and missing long-interval closures, obtained using long-term interferograms, such as 204-6 and 204-12.
Usage:
1. Ensure the interferograms from the first script are available.
2. Run the script to generate loop closures for the specified temporal baselines.
Example:
```bash
python PhaseBias_02_Loop_Closures.py
"""
if "--help" in sys.argv:
print(HELP_TEXT)
sys.exit(0)
################################################################################################
# Config file path
config_file = "config.txt"
# Check if config file exists
if not os.path.exists(config_file):
raise FileNotFoundError(
f"Error: The configuration file '{config_file}' was not found in the script's directory."
)
# Initialize the configparser
config = configparser.ConfigParser()
# Read the config.txt file
config.read(config_file)
# Define required parameters
required_parameters = [
"root_path",
"frame",
"start",
"end",
"interval",
"nlook",
"LiCSAR_data",
]
# Initialize a dictionary to store parameters
parameters = {}
# Attempt to retrieve each parameter and catch errors
try:
parameters["root_path"] = config.get("DEFAULT", "root_path")
parameters["output_path"] = config.get("DEFAULT", "output_path")
parameters["frame"] = config.get("DEFAULT", "frame")
parameters["start"] = config.get("DEFAULT", "start")
parameters["end"] = config.get("DEFAULT", "end")
parameters["interval"] = config.getint("DEFAULT", "interval")
parameters["nlook"] = config.getint(
"DEFAULT", "nlook") # Assuming 'nlook' should be an integer
parameters["LiCSAR_data"] = config.get("DEFAULT", "LiCSAR_data")
except configparser.NoOptionError as e:
# Error message if a required parameter is missing
missing_param = str(e).split(": ")[1]
raise ValueError(
f"Error: Required parameter '{missing_param}' is missing in '{config_file}'. Please check the file contents."
)
except configparser.Error as e:
# General error for any configparser-related issues
raise ValueError(f"Error while reading '{config_file}': {e}")
# Assign to individual variables for easy access
root_path = parameters["root_path"]
output_path = parameters["output_path"]
frame = parameters["frame"]
start = parameters["start"]
end = parameters["end"]
interval = parameters["interval"]
nlook = parameters["nlook"]
LiCSAR_data = parameters["LiCSAR_data"]
# hardcoded parameters, not included in the config file
landmask = 1
filtered_ifgs = "yes"
max_loop = 5 # in case of 3 all loops with 6,12,18-day will be calculated (e.g. (60,6), (60,12) and (60,18))
#############################################################################################
#################################################################################################
def loop_calc(max_loop):
## Read ifgs:
# Define the path components
sub_dir = "Data"
filename_pattern = "All_ifgs_*" # Pattern to match files starting with "All_ifgs"
# Construct the full file path with the refined pattern
file_path_pattern = os.path.join(output_path, sub_dir, filename_pattern)
# Use glob to find the file and ensure it exists
file_list = glob.glob(file_path_pattern)
if file_list:
file_path = file_list[0] # Get the single file path directly
# Load the data from the file
with open(file_path, "rb") as file:
all_ifgs = pickle.load(file)
else:
raise FileNotFoundError(
f"No file matching '{filename_pattern}' was found in '{os.path.join(output_dir, sub_dir)}'."
)
loop = {}
missing = {}
cat = sorted(all_ifgs.keys()) # Get sorted categories
# print('cat = ', cat)
# Initialize counters for reporting
loop_counts = {
category: {
cat[l]: 0
for l in range(max_loop)
}
for category in sorted(all_ifgs.keys())
}
missing_counts = {
category: {
cat[l]: 0
for l in range(max_loop)
}
for category in sorted(all_ifgs.keys())
}
for category in cat:
loop[category] = {
} # Initialize the key in the loop dictionary with an inner dictionary
missing[category] = [] # second ver
for l in range(
max_loop
): # it was up to 3 in the first version. but this allows to go for longer loops e.g. 288-72 (cat[11] is 72)
loop[category][cat[l]] = [
] # Initialize the key in the inner dictionary
# missing[cat[l]] = [] # first ver
# Calculate total iterations for progress percentage
total_iterations = sum(
len(all_ifgs[cat[i]]) for l in range(max_loop)
for i in range(1, len(cat))
if cat[i] % cat[l] == 0 and cat[i] != cat[l])
completed_iterations = 0
# Display the message before starting the progress bar
print(
f"Calculating all {interval}, {2 * interval}, and {3 * interval} loop closures."
)
for l in range(
0, max_loop
): # l could be 6, 12 and 18 to calculate e.g. 36-6 or 36-12 or 36-18
for i in range(1, len(cat)): # index for the category e.g. 6, 12, 18
if cat[i] % cat[l] == 0 and cat[i] != cat[
l]: # such as 12/6 or 24/12
for t in range(len(all_ifgs[
cat[i]])): # index for the epochs in each category
####################progress bar
completed_iterations += 1
percentage = (completed_iterations /
total_iterations) * 100
# Display progress percentage
sys.stdout.write("\rProgress: [{:<50}] {}%".format(
"=" * int(percentage // 2), int(percentage)))
sys.stdout.flush()
##################################
if cat[l] == interval:
end_index = t + int(cat[i] / cat[l])
# print('end_index = ', end_index)
else:
end_index = t + int(cat[i] / cat[l]) * int(
cat[l] / interval)
# recording the missing ifgs in each cat e.g. 6,12,18
#if np.any(np.array(all_ifgs[cat[i]])[t] == None):
if np.any(np.array(all_ifgs[cat[i]], dtype=object)[t] == None):
missing[cat[i]].append(
t
) # to record the missing ifgs index for each cateogory e.g. 18
# --- Check for overshoot(not enough data at the tail). this allows the calculate the missing in the next for loop
if end_index > len(all_ifgs[cat[l]]):
# Not enough short IFGs to form a valid closure → skip this loop
loop[cat[i]][cat[l]].append(None)
missing_counts[cat[i]][cat[l]] += 1
continue
for e in range(t, end_index, int(cat[l]/interval)): # to record the missing ifgs index for the period of each loop
#print(f" Long baseline (cat[i]): {cat[i]}")
#print(f" Short baseline (cat[l]): {cat[l]}")
#print(f" Index t: {t}, e: {e}, end_index: {end_index}")
#print(f" len(all_ifgs[cat[l]]): {len(all_ifgs[cat[l]])}")
elem = all_ifgs[cat[l]][e]
if elem is None:
missing[cat[l]].append(e)
if all_ifgs[cat[i]][t] is None or any(all_ifgs[cat[l]][elem] is None for elem in range(t, end_index, int(cat[l] / interval))):
loop[cat[i]][cat[l]].append(None)
missing_counts[cat[i]][cat[l]] += 1 # Increment missing loop counter
else:
closure = np.angle( np.exp( 1j * ( np.array(all_ifgs[cat[i]][t], dtype=np.float32)- np.sum( np.array(all_ifgs[cat[l]][t:end_index:int(cat[l] / interval)], dtype=np.float32), axis=0))))
if cat[i] in loop:
loop[cat[i]][cat[l]].append(closure)
loop_counts[cat[i]][cat[l]] += 1 # Increment successful loop counter
else:
loop[cat[i]][cat[l]] = [closure]
print("\n Finished calculating the loop closures.")
# Generate report
print("\n=== Loop Closure Report ===")
for category in [
2 * interval,
3 * interval,
]: # Restrict to relevant categories e.g. 18-6 and 12-6 as the main observations
for l in [interval]: # Restrict to the loop levels of interest
if category in loop_counts and l in loop_counts[category]:
generated = loop_counts[category].get(l, 0)
missing = missing_counts[category].get(l, 0)
print(
f"Loop Closure {category} - {l}: Generated = {generated}, Missing = {missing}"
)
print("\n=== Loop Closure Report for Long-interval Loop Closures ===")
# Iterate over categories greater than 200
for category in cat:
if category > 200: # Check for long categories
for l in range(
1,
5 * interval): # Check loop levels less than 5 * interval
if category in loop_counts and l in loop_counts[category]:
generated = loop_counts[category].get(l, 0)
if generated >= 1: # Only report if at least one loop is generated
print(
f"Loop Closure {category} - {l}: Generated = {generated}"
)
return loop, missing
################################################################################################
all_loops, missing = loop_calc(max_loop)
# Define the directory path
directory_path = os.path.join(output_path, "Data")
# Create the directory if it doesn't exist
os.makedirs(directory_path, exist_ok=True)
# Define the file path
file_path = os.path.join(directory_path, f"All_loops_{start}_{end}.pkl")
with open(file_path, "wb") as file: # for writting a dictionary to a file
pickle.dump(all_loops, file)
###
# Define the file path
file_path = os.path.join(directory_path, f"missing_loops")
with open(file_path, "wb") as file: # for writting a dictionary to a file
pickle.dump(missing, file)
@@ -0,0 +1,424 @@
#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
import pickle
import os
import sys
import glob
import configparser
import warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=DeprecationWarning)
################################################################################
HELP_TEXT = """
PhaseBias_03_calibration_pars.py
This script estimates the calibration parameters a_n using the loop closures calculated in the previous step.
The calibration parameters a_n are estimated by calculating the ratio of the long-term loop closure for the interferogram of interest to the long-term loop closure for the base interferogram. Assuming negligible bias in long-term interferograms, a_n is calculated as follows:
a_n = |φ(i,i+l) - Σ(t=i to i+l)φ(t,t+1+n)|_2π / |φ(i,i+l) - Σ(t=i to i+l)φ(t,t+1)|_2π
where:
- φ(i,i+l) is a long-term interferogram connecting epoch i to i+l.
- φ(t,t+1) represents the base interferogram.
- φ(t,t+1+n) is the short interferogram to be corrected using a_n.
### Input:
1. Loop closures from the previous step (e.g., 216-6, 216-12, and 216-18 for 6-day acquisition intervals).
2. The long-term interferogram length (e.g., 216 days) must be specified at the beginning.
3. The number of a_n parameters to estimate, specified using `num_a`. For example:
- Setting `num_a=2` indicates that a1 and a2 will be estimated (used to correct 12- and 18-day interferograms).
- For correcting longer interferograms, `num_a` should be set accordingly.
### Output:
1. All possible a_n values are calculated.
2. Visualizations:
- Example plots of a_n arrays and their corresponding histograms, illustrating spatial variations.
- Time-series plots showing how a_n values evolve over time.
3. Mean a_n values over time are output for further use.
### File Outputs:
- Results are stored in the output directory defined in the `config.txt` file under `/Data/` as `Mean_an_values.pkl`.
### Additional Notes:
- Users should ensure that `num_a` aligns with the desired temporal baselines for correction.
"""
if "--help" in sys.argv:
print(HELP_TEXT)
sys.exit(0)
###############################################################################
# Config file path
config_file = "config.txt"
# Check if config file exists
if not os.path.exists(config_file):
raise FileNotFoundError(
f"Error: The configuration file '{config_file}' was not found in the script's directory."
)
# Initialize the configparser
config = configparser.ConfigParser()
# Read the config.txt file
config.read(config_file)
# Define required parameters
required_parameters = [
"root_path",
"frame",
"start",
"end",
"interval",
"nlook",
"LiCSAR_data",
]
# Initialize a dictionary to store parameters
parameters = {}
# Attempt to retrieve each parameter and catch errors
try:
parameters["root_path"] = config.get("DEFAULT", "root_path")
parameters["output_path"] = config.get("DEFAULT", "output_path")
parameters["frame"] = config.get("DEFAULT", "frame")
parameters["start"] = config.get("DEFAULT", "start")
parameters["end"] = config.get("DEFAULT", "end")
parameters["interval"] = config.getint("DEFAULT", "interval")
parameters["nlook"] = config.getint(
"DEFAULT", "nlook"
) # Assuming 'nlook' should be an integer
parameters["num_a"] = config.getint("DEFAULT", "num_a")
parameters["LiCSAR_data"] = config.get("DEFAULT", "LiCSAR_data")
except configparser.NoOptionError as e:
# Error message if a required parameter is missing
missing_param = str(e).split(": ")[1]
raise ValueError(
f"Error: Required parameter '{missing_param}' is missing in '{config_file}'. Please check the file contents."
)
except configparser.Error as e:
# General error for any configparser-related issues
raise ValueError(f"Error while reading '{config_file}': {e}")
# Assign to individual variables for easy access
root_path = parameters["root_path"]
output_path = parameters["output_path"]
frame = parameters["frame"]
start = parameters["start"]
end = parameters["end"]
interval = parameters["interval"]
nlook = parameters["nlook"]
num_a = parameters["num_a"]
LiCSAR_data = parameters["LiCSAR_data"]
# hardcoded parameters, not included in the config file
landmask = 1
filtered_ifgs = "yes"
max_loop = 5 # in case of 3 all loops with 6,12,18-day will be calculated (e.g. (60,6), (60,12) and (60,18))
##################################################### Loop Closure calculation #####################################################
####################################################################################################################################
track = frame[0:3]
if track[0] == "0":
track = track[1:3]
if track[0] == "0":
track = track[1:2]
###################### Read coh:
print("\nReading all coherence data...")
# Define the path components
sub_dir = "Data"
filename_pattern = "All_coh_*" # Pattern to match files starting with "All_ifgs"
# Construct the full file path with the refined pattern
file_path_pattern = os.path.join(output_path, sub_dir, filename_pattern)
# Use glob to find the file and ensure it exists
file_list = glob.glob(file_path_pattern)
if file_list:
file_path = file_list[0] # Get the single file path directly
# Load the data from the file
with open(file_path, "rb") as file:
coh = pickle.load(file)
else:
raise FileNotFoundError(
f"No file matching '{filename_pattern}' was found in '{os.path.join(output_dir, sub_dir)}'."
)
print("Reading coherence data completed.")
##################### Read Loops
print("\nReading all loop closures...")
filename_pattern = "All_loops_*" # Pattern to match files starting with "All_ifgs"
# Construct the full file path with the refined pattern
file_path_pattern = os.path.join(output_path, sub_dir, filename_pattern)
# Use glob to find the file and ensure it exists
file_list = glob.glob(file_path_pattern)
if file_list:
file_path = file_list[0] # Get the single file path directly
# Load the data from the file
with open(file_path, "rb") as file:
all_loops = pickle.load(file)
else:
raise FileNotFoundError(
f"No file matching '{filename_pattern}' was found in '{os.path.join(output_dir, sub_dir)}'."
)
print("Reading loop closures completed.")
##################################################### Loop Closure calculation #####################################################
####################################################################################################################################
long_baseline = 216 # 36,72,108,144,180,216,252,288,324
coh_thresh = 25
def calc_an(loop_360_n, loop_360_6):
"""
Calculates the a_n values from loop closures.
Parameters:
loop_360_n (ndarray): Array of loop closures for n-day intervals.
loop_360_6 (ndarray): Array of loop closures for 6-day intervals.
Returns:
ndarray: Mean a_n values for all loop closures.
list: List of all a_n arrays for further processing or plotting.
"""
ratios = []
# Loop through indices
for i in range(len(loop_360_6)):
if loop_360_6[i] is not None and loop_360_n[i] is not None:
# Calculate the ratio for non-NaN elements
ratio_i = np.divide(
loop_360_n[i],
loop_360_6[i],
out=np.full_like(loop_360_n[i], np.nan),
where=~np.isnan(loop_360_6[i]),
)
ratios.append(ratio_i)
# Check if `ratios` is empty before proceeding
if not ratios:
print("Warning: No valid a_n values could be calculated. Returning NaN values.")
return np.array([np.nan]), []
# Convert the list of ratios to a numpy array
an = np.array(ratios, dtype=object)
mean_an_long_baseline = []
# Calculate mean values of each a_n
for arr in an:
mask = (arr > 0) & (arr < 1) # Apply mask to filter invalid values
arr[~mask] = np.nan
if not np.isnan(arr).all(): # Check if all elements are NaN
mean_an = np.nanmean(arr)
else:
mean_an = np.nan # Assign NaN for completely empty slices
mean_an_long_baseline.append(mean_an)
return np.array(mean_an_long_baseline), an
##################################################################################
############################
def plot_an(an_arrays, mean_a_long_baseline, k):
"""
Plots the a_n arrays with the largest coverage and their histograms in a two-row layout,
as well as the mean values of calibration parameters a_n over time.
Parameters:
an_arrays (list): List of a_n arrays.
mean_a_long_baseline (ndarray): Array of mean calibration parameter values for a_1, a_2, ..., a_n.
k (int): The current value of k (e.g., 2 for a1, 3 for a2).
"""
# Calculate the coverage (number of non-NaN values) for each array
coverage = []
valid_an_arrays = [] # Store only valid arrays for plotting
for arr in an_arrays:
if (
arr is not None and arr.ndim == 2 and not np.all(np.isnan(arr))
): # Check for valid 2D arrays
coverage.append(np.sum(~np.isnan(arr))) # Count non-NaN values
valid_an_arrays.append(arr)
# Sort arrays by coverage in descending order
sorted_indices = np.argsort(coverage)[::-1]
selected_arrays = [
valid_an_arrays[idx] for idx in sorted_indices[:6]
] # Select top 6 arrays
# Plot the a_n arrays and their histograms in a two-row layout
if selected_arrays:
num_arrays = len(selected_arrays)
fig = plt.figure(figsize=(4 * num_arrays, 8))
gs = GridSpec(
2, num_arrays + 1, width_ratios=[1] * num_arrays + [0.1]
) # Add space for colorbar
# Plot selected arrays
axes_img = []
for i, arr in enumerate(selected_arrays):
ax_img = fig.add_subplot(gs[0, i])
im = ax_img.imshow(arr, cmap="RdYlBu", vmin=-0.8, vmax=0.8)
ax_img.set_title(f"{i+1}th $a_{{{k-1}}}$ Array") # Dynamically set title
ax_img.axis("off")
axes_img.append(ax_img)
# Add a single colorbar for all array plots
cbar_ax = fig.add_subplot(gs[0, -1])
fig.colorbar(im, cax=cbar_ax, orientation="vertical", label="Color Scale")
# Plot histograms for the selected arrays
for i, arr in enumerate(selected_arrays):
ax_hist = fig.add_subplot(gs[1, i])
ax_hist.hist(arr.flatten(), bins=100, color="blue", alpha=0.7, density=True)
ax_hist.set_title(
f"{i+1}th $a_{{{k-1}}}$ Histogram"
) # Dynamically set title
ax_hist.set_xlim([-3, 3]) # Adjust histogram range as needed
plt.tight_layout()
plt.show()
else:
print("No valid a_n arrays available for plotting.")
# Plot the mean values of a_n over time
x_values = np.arange(len(mean_a_long_baseline)) # Sequential indices for x-axis
fig, ax = plt.subplots(figsize=(6, 4))
# Filter out NaN values to avoid gaps in the plot
valid_indices = ~np.isnan(mean_a_long_baseline) # Mask for valid (non-NaN) entries
x_valid = x_values[valid_indices] # Only use valid time steps
y_valid = np.array(mean_a_long_baseline)[valid_indices] # Only use valid a_n values
# Remove NaN values for trendline fitting
valid_indices = ~np.isnan(mean_a_long_baseline) # Mask for valid (non-NaN) entries
if (
valid_indices.sum() > 1
): # Ensure there are at least two valid points for fitting
# x_valid = x_values[valid_indices]
y_valid = np.array(mean_a_long_baseline)[valid_indices]
x_valid = np.arange(len(y_valid))
# Fit and plot a trendline
coefficients = np.polyfit(x_valid, y_valid, 1)
trendline = np.polyval(coefficients, x_valid)
ax.plot(x_valid, trendline, color="red", label="Trendline")
# Scatter plot for all points (including NaN if any)
ax.scatter(
#x_values,
#mean_a_long_baseline,
x_valid, # Only use valid time steps
y_valid, # Only use valid a_n values
color="blue",
marker="o",
label="Mean Values",
s=9,
)
# Set labels and limits
ax.set_ylim(-3, 3) # Adjust limits as needed
ax.set_xlabel("Time Step") # Sequential index as x-axis
ax.set_ylabel("Mean Values", fontsize=12)
ax.legend()
# Adjust layout and show the plot
plt.tight_layout()
plt.show()
##
######### forming 360-6
loop_360_6_all = np.array(all_loops[long_baseline][interval], dtype=object)
coh_360 = np.array(coh[long_baseline][:], dtype=object)
loop_360_6 = np.full_like(
loop_360_6_all, np.nan
) # create a new array as the same size of loop_360_6_all with nan values
for i, arr in enumerate(loop_360_6_all):
if arr is not None:
(frame_row, frame_col) = np.shape(arr)
loop_360_6[i] = np.where((coh_360[i] > coh_thresh), arr, np.nan)
###### forming 360-n (n=12,18,24 etc)
# mean_a_long_baseline = []
final_mean_values = []
an_labels = []
# Loop through the values of k corresponding to the number of calibration parameters
for k in range(2, 2 + num_a): # k=2 for a1, k=3 for a2, etc.
mean_an_long_baseline = []
# Forming 360-n (n=12, 18, 24, etc.)
loop_360_n_all = np.array(all_loops[long_baseline][k * interval], dtype=object)
loop_360_n = np.full_like(loop_360_n_all, np.nan)
for i, arr in enumerate(loop_360_n_all):
if arr is not None:
# Apply coherence threshold filtering
loop_360_n[i] = np.where((coh_360[i] > coh_thresh), arr, np.nan)
# Calculate a_n values
mean_an_long_baseline, an_arrays = calc_an(loop_360_n, loop_360_6)
# If all values in mean_an_long_baseline are nan (empty ratios), stop execution
if np.isnan(mean_an_long_baseline).all():
print("No valid a_n values could be calculated. Stopping execution.")
sys.exit(1) # Exit the script with an error code (1 means failure)
# Calculate the mean of all mean values for this k and store it
overall_mean = np.nanmean(mean_an_long_baseline)
final_mean_values.append(overall_mean)
an_labels.append(f"a{k-1}")
for idx, mean_a in enumerate(mean_an_long_baseline, start=1):
if not np.isnan(mean_a): # Check if the value is not NaN
print(f"Mean of the {idx}th a({k-1}) is {mean_a:.6f}")
plot_an(an_arrays, mean_an_long_baseline, k)
# Print the final mean values across all k
for k_idx, final_mean in enumerate(final_mean_values, start=2):
print(f"Final mean value for a({k_idx-1}) is {final_mean:.6f}")
# Write final mean values to a text file
output_path = os.path.join(parameters["output_path"], "Data")
os.makedirs(output_path, exist_ok=True) # Create directory if it doesn't exist
output_file = os.path.join(output_path, "an.txt")
with open(output_file, "w") as file:
for label, mean_value in zip(an_labels, final_mean_values):
file.write(f"{label}={mean_value:.6f}\n")
print(f"Final mean values written to {output_file}.")
@@ -0,0 +1,683 @@
#!/usr/bin/env python3
import numpy as np
import pickle
import os
from scipy.sparse import csc_array
from scipy.sparse.linalg import lsqr
import sys
import math
from bin.read_orig_ifgs_coh import read_orig_ifgs_coh
from bin.circular_mean_var import circular_mean_and_variance_over_epochs
import glob
import configparser
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
################################################################################
HELP_TEXT = """
PhaseBias_04_Inversion.py
This script estimates the phase bias terms for the base interferograms using short-term closure phases as input.
The bias terms derived in this step serve as the foundation for correcting other short-term interferograms.
### Workflow:
1. **Masking Noisy Loop Closures:**
- A moving average is applied to the time-series of loop closures to account for seasonal fluctuations.
- A circular moving average (mean of complex values over time) is computed for each pixel.
- The distance of each loop closure from the moving average is calculated. If the distance exceeds a threshold (2σ), the point is masked as noisy.
- The circular standard deviation (σ) is computed using the von Mises distribution (circular normal distribution).
2. **Refined Loop Closures:**
- Masked loop closures, denoted as 〖Δφ〗_(i,i+2)^r and 〖Δφ〗_(i,i+3)^r, are used as primary observations for phase bias estimation.
3. **First Inversion (Without Temporal Smoothing Constraints):**
- Estimates the bias terms that can be corrected directly from the observed loop closures.
4. **Second Inversion (With Temporal Smoothing Constraints):**
- Incorporates temporal smoothing constraints to estimate additional bias terms that cannot be directly derived from loop closures.
- The temporal smoothing minimizes differences between bias terms over time, ensuring consistency.
5. **Combining Results:**
- Bias terms from the first inversion are combined with the results of the second inversion to include terms not estimated in the first round.
### Outputs:
- The phase bias terms for the base interferograms are stored as a NumPy array file:
- `X_base_ifgs_biases.npy`, saved in the `Data` directory under the `output_path` defined in `config.txt`.
### Input Requirements:
- Short-term closure phases (from `PhaseBias_02_Loop_Closures.py`).
- Configuration parameters, including thresholds and temporal settings, defined in `config.txt`.
### Output Files:
- `X_base_ifgs_biases.npy`: Stores the estimated bias terms for the base interferograms.
"""
if "--help" in sys.argv:
print(HELP_TEXT)
sys.exit(0)
###############################################################################
# Config file path
config_file = "config.txt"
# Check if config file exists
if not os.path.exists(config_file):
raise FileNotFoundError(
f"Error: The configuration file '{config_file}' was not found in the script's directory."
)
# Initialize the configparser
config = configparser.ConfigParser()
# Read the config.txt file
config.read(config_file)
# Define required parameters
required_parameters = [
"root_path",
"frame",
"start",
"end",
"interval",
"nlook",
"LiCSAR_data",
"a1_6_day",
"a2_6_day",
"a1_12_day",
"a2_12_day",
"estimate_an_values",
]
# Initialize a dictionary to store parameters
parameters = {}
# Attempt to retrieve each parameter and catch errors
try:
parameters["root_path"] = config.get("DEFAULT", "root_path")
parameters["output_path"] = config.get("DEFAULT", "output_path")
parameters["frame"] = config.get("DEFAULT", "frame")
parameters["start"] = config.get("DEFAULT", "start")
parameters["end"] = config.get("DEFAULT", "end")
parameters["interval"] = config.getint("DEFAULT", "interval")
parameters["nlook"] = config.getint(
"DEFAULT", "nlook"
) # Assuming 'nlook' should be an integer
parameters["LiCSAR_data"] = config.get("DEFAULT", "LiCSAR_data")
parameters["a1_6_day"] = config.getfloat("DEFAULT", "a1_6_day")
parameters["a2_6_day"] = config.getfloat("DEFAULT", "a2_6_day")
parameters["a1_12_day"] = config.getfloat("DEFAULT", "a1_12_day")
parameters["a2_12_day"] = config.getfloat("DEFAULT", "a2_12_day")
parameters["estimate_an_values"] = config.get("DEFAULT", "estimate_an_values")
except configparser.NoOptionError as e:
# Error message if a required parameter is missing
missing_param = str(e).split(": ")[1]
raise ValueError(
f"Error: Required parameter '{missing_param}' is missing in '{config_file}'. Please check the file contents."
)
except configparser.Error as e:
# General error for any configparser-related issues
raise ValueError(f"Error while reading '{config_file}': {e}")
# Assign to individual variables for easy access
root_path = parameters["root_path"]
output_path = parameters["output_path"]
frame = parameters["frame"]
start = parameters["start"]
end = parameters["end"]
interval = parameters["interval"]
nlook = parameters["nlook"]
LiCSAR_data = parameters["LiCSAR_data"]
estimate_an_values = parameters["estimate_an_values"]
# Initialize a1 and a2 with None for safety
a1 = None
a2 = None
print("estimate_an_values is ", estimate_an_values)
# Check if estimate_an_values is 'yes'
if estimate_an_values == "yes":
an_file_path = os.path.join(output_path, "Data", "an.txt")
# Try reading the file
try:
if os.path.exists(an_file_path):
print(f"Reading 'a' values from {an_file_path}...")
# Read the file and load the values
with open(an_file_path, "r") as file:
for line in file:
line = line.strip()
if line.startswith("a1="):
a1 = float(line.split("=")[1])
elif line.startswith("a2="):
a2 = float(line.split("=")[1])
# Check if both a1 and a2 were found
if a1 is None or a2 is None:
print(
"Warning: Missing a1 or a2 in an.txt. Switching to default values from config file."
)
raise ValueError("Incomplete a1 or a2 values.")
else:
print(
f"Warning: {an_file_path} does not exist. Switching to default values from config file."
)
raise FileNotFoundError
except (FileNotFoundError, ValueError):
# Fallback to default values from config file
if interval == 6:
a1 = parameters["a1_6_day"]
a2 = parameters["a2_6_day"]
else:
a1 = parameters["a1_12_day"]
a2 = parameters["a2_12_day"]
else:
# Use default values from the config file
print("Using default 'an' values from the config file.")
if interval == 6:
a1 = parameters["a1_6_day"]
a2 = parameters["a2_6_day"]
else:
a1 = parameters["a1_12_day"]
a2 = parameters["a2_12_day"]
# Print the chosen values
print(f"Final values - a1: {a1}, a2: {a2}")
##################################################### Loop Closure calculation #####################################################
####################################################################################################################################
####################################################################################################################################
track = frame[0:3]
if track[0] == "0":
track = track[1:3]
if track[0] == "0":
track = track[1:2]
with_temporals = "yes" # it should be yes, if you want to incorporate the temporal constraints
apply_to_all = "no" # in case of with_temporal='yes', we can decide if you want to use the temporal to all ifgs (i.e. apply_to_all='yes'), or just to those that can not be corrected (i.e. apply_to_all='no')
w = 0.1 # the weigth of the temporal smoothing constraints
#######
coh_thresh = 11 # threhsold on the coherence values. In this version it is off
min_num_eq = 10 # I used 10 in all my experiments. min number of equations in the least square inversion.
############################### Reading input data #############################################
#################### Read ifgs:
print("Reading all ifgs...")
# Define the path components
sub_dir = "Data"
filename_pattern = "All_ifgs_*" # Pattern to match files starting with "All_ifgs"
# Construct the full file path with the refined pattern
file_path_pattern = os.path.join(output_path, sub_dir, filename_pattern)
# Use glob to find the file and ensure it exists
file_list = glob.glob(file_path_pattern)
if file_list:
file_path = file_list[0] # Get the single file path directly
# Load the data from the file
with open(file_path, "rb") as file:
all_ifgs = pickle.load(file)
else:
raise FileNotFoundError(
f"No file matching '{filename_pattern}' was found in '{os.path.join(output_dir, sub_dir)}'."
)
print("Reading ifgs completed.")
###################### Read coh:
print("\nReading all coherence data...")
# Define the path components
sub_dir = "Data"
filename_pattern = "All_coh_*" # Pattern to match files starting with "All_ifgs"
# Construct the full file path with the refined pattern
file_path_pattern = os.path.join(output_path, sub_dir, filename_pattern)
# Use glob to find the file and ensure it exists
file_list = glob.glob(file_path_pattern)
if file_list:
file_path = file_list[0] # Get the single file path directly
# Load the data from the file
with open(file_path, "rb") as file:
all_coh = pickle.load(file)
else:
raise FileNotFoundError(
f"No file matching '{filename_pattern}' was found in '{os.path.join(output_dir, sub_dir)}'."
)
print("Reading coherence data completed.")
##################### Read Loops
print("\nReading all loop closures...")
filename_pattern = "All_loops_*" # Pattern to match files starting with "All_ifgs"
# Construct the full file path with the refined pattern
file_path_pattern = os.path.join(output_path, sub_dir, filename_pattern)
# Use glob to find the file and ensure it exists
file_list = glob.glob(file_path_pattern)
if file_list:
file_path = file_list[0] # Get the single file path directly
# Load the data from the file
with open(file_path, "rb") as file:
all_loops = pickle.load(file)
else:
raise FileNotFoundError(
f"No file matching '{filename_pattern}' was found in '{os.path.join(output_dir, sub_dir)}'."
)
print("Reading loop closures completed.")
all_cat = []
for cat in all_loops:
all_cat.append(cat)
### stacking all the ifgs 6/12/18 in a numpy var all_ifgs
print(
"Extracting the required interferograms(up to 3 epochs), and the corresponding loop closures for inversion..."
)
desired_categories = [interval, 2 * interval, 3 * interval]
all_ifgs, _, existing_ifgs_index = read_orig_ifgs_coh(
all_ifgs, all_coh, desired_categories
)
######### forming 12-6 and 18-6 loop closures from the imported data
#################################################################
loop_12 = np.array(all_loops[2 * interval][interval], dtype=object)
#loop_12 = np.array(all_loops[2 * interval][interval])
#coh_12 = np.array(all_coh[2 * interval][:])
coh_12 = np.array(all_coh[2 * interval][:], dtype=object)
#loop_18 = np.array(all_loops[3 * interval][interval])
#coh_18 = np.array(all_coh[3 * interval][:])
loop_18 = np.array(all_loops[3 * interval][interval], dtype=object)
coh_18 = np.array(all_coh[3 * interval][:], dtype=object)
############## finding dynamic pixel-based thresholds to remove the noisy loops
loop_12_orig = []
loop_18_orig = []
none_indices12 = []
none_indices18 = []
# refine loop_12 to exclude the none indices and create loop_12_orig
for i, arr in enumerate(loop_12):
if arr is not None:
(frame_row, frame_col) = np.shape(arr)
loop_12_orig.append(arr)
else:
none_indices12.append(i)
# refine loop_18 to exclude the none indices and create loop_18_orig
for i, arr in enumerate(loop_18):
if arr is not None:
loop_18_orig.append(arr)
else:
none_indices18.append(i)
loop_12_orig = np.array(loop_12_orig)
loop_18_orig = np.array(loop_18_orig)
### removing noisy loops
print(
"Masking noisy loop closures using circular moving average and standard deviaiton of the loop closures in time:"
)
# using circular_mean to calculate the mean phase value using complex numbers, and von_mises_variance to calculate the second moment of the Von Mises distribution
_, thresh_loop12 = circular_mean_and_variance_over_epochs(loop_12_orig, axis=0)
_, thresh_loop18 = circular_mean_and_variance_over_epochs(loop_18_orig, axis=0)
# Add a new axis at the beginning (axis=0) of these arrays to have shape (1, ...)
# These are the threshold vlaues obtained for each pixel that will be used for masking later
thresh_loop12 = np.expand_dims(thresh_loop12, axis=0)
thresh_loop18 = np.expand_dims(thresh_loop18, axis=0)
# calculate a temporal moving average for wrapped data
def moving_average(arr, window_size):
# Initialize an empty array to store the temporal averages
moving_averages = np.zeros_like(arr)
half_window = window_size // 2
### miroring data at both ends for window_size/2 at each end
mirrored_shape = (arr.shape[0] + window_size, arr.shape[1], arr.shape[2])
# Create an empty array to hold the mirrored data
mirrored_arr = np.empty(mirrored_shape, dtype=arr.dtype)
# Fill the mirrored array with the original data
mirrored_arr[window_size // 2 : -window_size // 2] = arr
# Mirror the data at the beginning
for i in range(window_size // 2):
# mirrored_arr[i] = arr[window_size // 2 - i]
mirrored_arr[i] = arr[min(half_window - i, arr.shape[0] - 1)]
# Mirror the data at the end
for i in range(window_size // 2):
# mirrored_arr[-(i + 1)] = arr[-(i + 1) - window_size // 2]
mirrored_arr[-(i + 1)] = arr[max(-1 - (half_window - i), 0)]
####
# Calculate temporal averages within each window
for t in range(half_window, mirrored_arr.shape[0] - half_window):
moving_averages[t - half_window, :, :] = np.angle(
np.nanmean(
np.exp(1j * (mirrored_arr[t - half_window : t + half_window, :, :])),
axis=0,
)
)
return moving_averages
# for loop 12
# Calculate distance between each epoch and the moving average for each pixel
print(
f"Calculating the moving average for {2 * interval} loop closures, followed by masking noisy loop closures..."
)
print(
"This may take a while, as it depends on the number of loops and the size of your dataset.\n"
)
window_size = 30
moving_avg = moving_average(loop_12_orig, window_size)
distances = np.abs(np.angle(np.exp(1j * (loop_12_orig - moving_avg))))
mask = distances > 2 * thresh_loop12 # it is 4*sigma
# Replace values with NaN where mask is True
loop_12_bk = loop_12_orig
loop_12_orig = np.where(mask, np.nan, loop_12_orig)
loop_12 = loop_12_orig.tolist()
for idx in none_indices12:
loop_12.insert(idx, None)
loop_12 = np.array(loop_12, dtype=object)
# for loop 18
# Calculate distance between each epoch and the moving average for each pixel
print(
f"Calculating the moving average for {3 * interval} loop closures, followed by masking noisy loop closures..."
)
print(
"This may take a while, as it depends on the number of loops and the size of your dataset.\n"
)
moving_avg = moving_average(loop_18_orig, window_size)
distances = np.abs(np.angle(np.exp(1j * (loop_18_orig - moving_avg))))
mask = distances > 2 * thresh_loop18 # it is 4*sigma
# Replace values with NaN where mask is True
loop_18_bk = loop_18_orig
loop_18_orig = np.where(mask, np.nan, loop_18_orig)
loop_18 = loop_18_orig.tolist()
for idx in none_indices18:
loop_18.insert(idx, None)
loop_18 = np.array(loop_18, dtype=object)
print("Masking of noisy loop closures is completed.")
# ################ Apply coherece thresholding
# print('shape loop_12 = ', np.shape(loop_12))
# print('shape loop_12_orig = ', np.shape(loop_12_orig))
# print('shape coh_12 = ', np.shape(coh_12))
# for i, arr in enumerate(loop_12):
# if arr is not None:
# (frame_row, frame_col) = np.shape(arr)
# loop_12[i] = np.where((coh_12[i] > coh_thresh), arr, np.nan)
#
#
# for i, arr in enumerate(loop_18):
# if arr is not None:
# loop_18[i] = np.where((coh_18[i] > coh_thresh), arr, np.nan)
#
#
#
len12 = len(loop_12) # number of 12 day loops including None
len18 = len(loop_18) # number of 18 day loops including None
######################## Forming the design matrix A ##############################
####################################################################################
print("Preparing the design matrix and observation vector for the inversion step...")
b = []
A = []
n_unk = (
len12 + 1
) # this in an initial value(i.e. the num of 6 biases). will be changed by the actual number of unk after considering the None values/missing
# print('n_unk = ', n_unk)
row = np.zeros(
n_unk, dtype=np.float32
) # each row of the design matrix A for the 12-day
for i in range(len12):
b.append(loop_12[i])
# print('np.shape(loop_12[i] = ', np.shape(loop_12[i]))
row[i : i + 2] = a1 - 1
A.append(row)
row = np.zeros(n_unk, dtype=np.float32)
row = np.zeros(
n_unk, dtype=np.float32
) # each row of the design matrix A for the 18-day
for i in range(len18):
b.append(loop_18[i])
row[i : i + 3] = a2 - 1
A.append(row)
row = np.zeros(n_unk, dtype=np.float32)
A = np.array(A)
b = np.array(b, dtype=object)
####################### removing the rows from b and A where b is None
mask = []
mask = np.array([arr is not None for arr in b])
# Convert the boolean mask to an integer mask
mask = np.nonzero(mask)
A = A[mask] # Filter rows of A based on the mask
b = b[mask]
b = b.tolist()
############ removing the columns of A where are values are zero (these are the unkonws which doesn't fall in any equations nor 12 neither 18 and thus cannot be corrected)
# Find the column indices where all values are zero
zero_columns = np.all(A == 0, axis=0)
## Get the indices of the zero columns
zero_column_indices = np.where(zero_columns)[0]
# Get the indices of the non-zero columns
non_zero_column_indices = np.where(~zero_columns)[
0
] # the indices of the unknowns that can be corrected
# Save the file
directory_path = os.path.join(output_path, "Data")
file_path = os.path.join(directory_path, f"indices_unknown_tobe_corrected.npy")
np.save(file_path, non_zero_column_indices)
### Adding all the existing 6-day ifgs indices to non_zero_column_indices. We want to use estimate their biases in the second step.
A_bk = A # to keep a copy of A in case we want to esimate all 6-day biases with smoothing constraints
b_bk = b
all_column_indices = np.array(
range(A_bk.shape[1])
) # generating all indices in case we want to esimate all 6-day biases with smoothing constraints
A = A[:, non_zero_column_indices]
# finding the last column with value -1. this gives the number of 6-day biases that can be corrected
last_column_with_minus_1 = None
# Iterate through the columns from right to left
for col in range(len(A[0]) - 1, -1, -1):
if -1 in [row[col] for row in A]:
last_column_with_minus_1 = col
break
num_rows_before_temporals = A.shape[0]
################################# Least Square inversion ###############################
########################################################################################
# First Inversion: Without Temporal Smoothing Constraints
print("Starting the first inversion (without temporal smoothing constraints).")
print(
"This step estimates the bias terms that can be corrected based on observed loop closures."
)
damp_factor = 0
if apply_to_all == "no": # this is without using any temporal constraints
X1 = np.zeros((np.shape(A_bk)[1], frame_row, frame_col), dtype=np.float32)
# X1[:,:,:] = np.nan # after checking noticed this doesn't have any effect on the final vel
b_bk = np.array(b_bk)
total_pixels = frame_row * frame_col # Total number of pixels for progress bar
processed_pixels = 0 # Counter for processed pixels
print("Progress: [", end="", flush=True)
for row in range(frame_row):
for col in range(frame_col):
processed_pixels += 1
# Update progress bar
percentage = (processed_pixels / total_pixels) * 100
if processed_pixels % (total_pixels // 100) == 0: # Update every 1%
print(f"{int(percentage)}%", end="", flush=True)
sys.stdout.write(
"\rProgress: ["
+ "=" * (int(percentage) // 2)
+ " " * (50 - int(percentage) // 2)
+ "]"
)
non_nan_mask = ~np.isnan(b_bk[:, row, col])
bb = b_bk[non_nan_mask, row, col] # Remove NaN values
AA = A_bk[non_nan_mask, :] # Remove corresponding rows
if len(bb) > min_num_eq: # what is the min number of equation?
x, istop, itn, normr, normr2 = lsqr(
csc_array(AA), bb, damp=damp_factor
)[
:5
] # Using sparse matrix representation scipy.sparse.linalg
X1[:, row, col] = x
# if with_temporals == "no": # this solution will be the final answer to be saved as X
# # Fill X with values from X1 according to non_zero_column_indices
# for i, idx in enumerate(non_zero_column_indices):
# X[idx, :, :] = X1[i, :, :]
print("\nFirst inversion (without temporal smoothing constraints) completed.")
###########################
# Second Inversion: With Temporal Smoothing Constraints
print("Starting the second inversion (with temporal smoothing constraints).")
print(
"This step estimates all bias terms, including those that cannot be corrected, using temporal smoothing constraints."
)
if with_temporals == "yes": # This is using the temporal constranints on all unknowns
X2 = np.zeros((np.shape(A_bk)[1], frame_row, frame_col), dtype=np.float32)
# X2[:,:,:] = np.nan # after checking noticed this doesn't have any effect on the final vel
b_bk = np.array(b_bk)
#### Adding temporal constraints
row = np.zeros(
A_bk.shape[1], dtype=np.float32
) # additional rows the design matrix A for temporal constraints, setting that to zero again
for i in range(len(all_column_indices) - 2): # for all unknowns
row[i] = -1 * w
row[i + 1] = 2 * w
row[i + 2] = -1 * w
A_bk = np.vstack((A_bk, row))
row = np.zeros(
A_bk.shape[1], dtype=np.float32
) # additional rows the design matrix A for temporal constraints, setting that to zero again
num_temporals = len(A_bk) - len(b_bk)
# print('num_temporals is ', num_temporals)
######### Appending zeroes to b according to the added number of temporal constraints obtained by np.shape(A)[0] - np.shape(b)[0]
b_0 = np.zeros(
(np.shape(A_bk)[0] - np.shape(b)[0], frame_row, frame_col), dtype=np.float32
)
b_bk = np.vstack((b_bk, b_0))
thresh_n_eq = num_temporals # in case of using temporals, we don't want the nan pixels with zero equations with only using temporals
processed_pixels = 0 # Reset counter for second inversion
print("Progress: [", end="", flush=True)
for row in range(frame_row):
for col in range(frame_col):
processed_pixels += 1
# Update progress bar
percentage = (processed_pixels / total_pixels) * 100
if processed_pixels % (total_pixels // 100) == 0: # Update every 1%
print(f"{int(percentage)}%", end="", flush=True)
sys.stdout.write(
"\rProgress: ["
+ "=" * (int(percentage) // 2)
+ " " * (50 - int(percentage) // 2)
+ "]"
)
non_nan_mask = ~np.isnan(b_bk[:, row, col])
bb = b_bk[non_nan_mask, row, col] # Remove NaN values
AA = A_bk[non_nan_mask, :] # Remove corresponding rows
if len(bb) > thresh_n_eq:
x, istop, itn, normr, normr2 = lsqr(
csc_array(AA), bb, damp=damp_factor
)[
:5
] # Using sparse matrix representation scipy.sparse.linalg
X2[:, row, col] = x
print("\nSecond inversion (with temporal smoothing constraints) completed.")
####### combining X1 and X2 into X
X = np.zeros((np.shape(A_bk)[1], frame_row, frame_col), dtype=np.float32)
X[:, :, :] = np.nan
# Fill X with values from X1 according to non_zero_column_indices
for i, idx in enumerate(non_zero_column_indices):
X[idx, :, :] = X1[i, :, :]
# Fill in the missing values from X2
for i, idx in enumerate(all_column_indices):
if idx not in non_zero_column_indices:
X[idx, :, :] = X2[i, :, :]
# Ensure the dtype is appropriate for your data
X = X.astype(np.float32)
directory_path = os.path.join(output_path, "Data")
file_path = os.path.join(directory_path, f"X_base_ifgs_biases.npy")
np.save(file_path, X)
print("Inversion process completed. Results saved to:", file_path)
##########################################################################################################
@@ -0,0 +1,535 @@
#!/usr/bin/env python3
import numpy as np
from datetime import datetime
import pickle
import time
import os
from bin.generate_ifgs_from_epochs import generate_ifg_pairs
import configparser
import glob
from bin.resample import resample_geotiff
import sys
# sys.path.append(os.path.dirname(os.path.abspath(__file__)))
import bin
from bin.read_orig_ifgs_coh import read_orig_ifgs_coh
from bin.ifg_cc_totif import ifg_cc_2tif
import gc
###############################################################################
HELP_TEXT = """
PhaseBias_05_Correction.py
This script applies phase bias correction to desired interferograms using the estimated bias terms for the base interferograms. The corrected interferograms are saved in GeoTIFF format for further analysis.
### Workflow:
1. **Inputs:**
- **Original Wrapped Interferograms, and Coherence Data:** Obtained from step 1 (`PhaseBias_01_Read_Data.py`).
- **Estimated Bias Terms for Base Intierferograms:** Obtained from step 4 (`PhaseBias_04_Inversion.py`).
- **Calibration Parameters (*a_n*):** Estimated from step 3 (`PhaseBias_03_calibration_pars.py`).
- **max_con:** Defines the maximum number of connections to be corrected. For instance:
- `max_con=5` corrects interferograms up to 30-day intervals for a 6-day acquisition interval.
- Adjust `max_con` as needed.
2. **Bias Term Estimation for Desired Interferograms:**
- Bias terms for desired interferograms, δ_(i,i+n+1), are estimated using the relationship:
δ_(i,i+n+1) = a_n * (∑_(t=i)^(i+n) δ_(t,t+1) )
3. **Correction of Interferograms:**
- Using the estimated bias terms, the interferograms are corrected as follows:
φ_(i,i+n+1)^c = φ_(i,i+n+1) - δ_(i,i+n+1)
- Here, φ_(i,i+n+1) is the original interferogram, and φ_(i,i+n+1)^c is the corrected interferogram.
4. **Outputs:**
- Corrected interferograms are saved in GeoTIFF format in the `GEOC` directory under the `output_path` specified in `config.txt`.
### Output File Format:
- **Corrected Interferograms:** Saved in GeoTIFF format, organized by temporal baseline.
### Input Requirements:
- Original wrapped interferograms from step 1.
- Bias terms for base interferograms from step 4.
- Configuration parameters (e.g., `output_path`, `interval`) defined in `config.txt`.
### Output Directory:
- `GEOC` directory under `output_path`: Contains the corrected interferograms in GeoTIFF format, organized by temporal baseline.
"""
if "--help" in sys.argv:
print(HELP_TEXT)
sys.exit(0)
################################################################################
# Config file path
config_file = "config.txt"
# Check if config file exists
if not os.path.exists(config_file):
raise FileNotFoundError(
f"Error: The configuration file '{config_file}' was not found in the script's directory."
)
# Initialize the configparser
config = configparser.ConfigParser()
# Read the config.txt file
config.read(config_file)
print("Config keys:", list(config.defaults().keys()))
# Define required parameters
required_parameters = [
"root_path",
"frame",
"start",
"end",
"interval",
"nlook",
"LiCSAR_data",
"a1_6_day",
"a2_6_day",
"a3_6_day",
"a4_6_day",
"a1_12_day",
"a2_12_day",
"a3_12_day",
"a4_12_day",
"estimate_an_values",
]
# Initialize a dictionary to store parameters
parameters = {}
# Attempt to retrieve each parameter and catch errors
try:
parameters["root_path"] = config.get("DEFAULT", "root_path")
parameters["output_path"] = config.get("DEFAULT", "output_path")
parameters["frame"] = config.get("DEFAULT", "frame")
parameters["start"] = config.get("DEFAULT", "start")
parameters["end"] = config.get("DEFAULT", "end")
parameters["interval"] = config.getint("DEFAULT", "interval")
parameters["nlook"] = config.getint(
"DEFAULT", "nlook"
) # Assuming 'nlook' should be an integer
parameters["LiCSAR_data"] = config.get("DEFAULT", "LiCSAR_data")
parameters["a1_6_day"] = config.getfloat("DEFAULT", "a1_6_day")
parameters["a2_6_day"] = config.getfloat("DEFAULT", "a2_6_day")
parameters["a3_6_day"] = config.getfloat("DEFAULT", "a3_6_day")
parameters["a4_6_day"] = config.getfloat("DEFAULT", "a4_6_day")
parameters["a1_12_day"] = config.getfloat("DEFAULT", "a1_12_day")
parameters["a2_12_day"] = config.getfloat("DEFAULT", "a2_12_day")
parameters["a3_12_day"] = config.getfloat("DEFAULT", "a3_12_day")
parameters["a4_12_day"] = config.getfloat("DEFAULT", "a4_12_day")
parameters["estimate_an_values"] = config.get("DEFAULT", "estimate_an_values")
except configparser.NoOptionError as e:
# Error message if a required parameter is missing
missing_param = str(e).split(": ")[1]
raise ValueError(
f"Error: Required parameter '{missing_param}' is missing in '{config_file}'. Please check the file contents."
)
except configparser.Error as e:
# General error for any configparser-related issues
raise ValueError(f"Error while reading '{config_file}': {e}")
# Assign to individual variables for easy access
root_path = parameters["root_path"]
output_path = parameters["output_path"]
frame = parameters["frame"]
start = parameters["start"]
end = parameters["end"]
interval = parameters["interval"]
nlook = parameters["nlook"]
LiCSAR_data = parameters["LiCSAR_data"]
estimate_an_values = parameters["estimate_an_values"]
start_date = datetime.strptime(start, "%Y%m%d")
end_date = datetime.strptime(end, "%Y%m%d")
uncor_only = 1 # in case of 1 only uses 6-12-18 uncorrected ifgs. it is based on the desired_lengths ifgs
max_con = 5 # in case of 5, it will correct up to 6*5=30-day ifgs.
#####################################################
# Root directory where the category directories are located
if LiCSAR_data == "yes":
track = frame[0:3] # extracting track number from frame id
if track[0] == "0":
track = track[1:3]
if track[0] == "0":
track = track[1:2]
root_directory = (
f"/gws/nopw/j04/nceo_geohazards_vol1/public/LiCSAR_products/{track}/{frame}"
)
else:
root_directory = root_path
############################################
# Initialize the an values with None for safety
an_values = [None] * (
max_con - 1
) # For max_con=5, this will create [None, None, None, None]
print("estimate_an_values is ", estimate_an_values)
# Check if estimate_an_values is 'yes'
if estimate_an_values == "yes":
an_file_path = os.path.join(output_path, "Data", "an.txt")
# Try reading the file
try:
if os.path.exists(an_file_path):
print(f"Reading 'a' values from {an_file_path}...")
# Read the file and load the an values dynamically
with open(an_file_path, "r") as file:
for line in file:
line = line.strip()
for i in range(
1, max_con
): # Loop through a1, a2, ..., a(max_con-1)
param_name = f"a{i}"
if line.startswith(f"{param_name}="):
an_values[i - 1] = float(line.split("=")[1])
# Check if all required an values were found
if any(value is None for value in an_values):
print(
"Warning: Missing one or more an values in an.txt. Switching to default values from config file."
)
raise ValueError("Incomplete an values.")
else:
print(
f"Warning: {an_file_path} does not exist. Switching to default values from config file."
)
raise FileNotFoundError
except (FileNotFoundError, ValueError):
# Fallback to default values from config file
print("Loading default 'an' values from config file...")
for i in range(1, max_con):
if interval == 6:
an_values[i - 1] = parameters[f"a{i}_6_day"]
else:
an_values[i - 1] = parameters[f"a{i}_12_day"]
else:
# Use default values from the config file
print("Using default 'an' values from the config file.")
for i in range(1, max_con):
if interval == 6:
an_values[i - 1] = parameters[f"a{i}_6_day"]
else:
an_values[i - 1] = parameters[f"a{i}_12_day"]
# Print the chosen an values
for i, value in enumerate(an_values, start=1):
print(f"Final value - a{i}: {value}")
############## generating ifg pairs between two epochs
# desired_lengths = [interval, 2*interval, 3*interval, 4*interval, 5*interval]
desired_lengths = [interval * i for i in range(1, max_con + 1)] # replacing the above
all_ifgs_string = generate_ifg_pairs(start_date, end_date, interval, desired_lengths)
##### reading original ifgs/coh #############################
####################################################################################
############################### Reading input data #############################################
#################### Read ifgs:
print("Reading all ifgs...")
# Define the path components
sub_dir = "Data"
filename_pattern = "All_ifgs_*" # Pattern to match files starting with "All_ifgs"
# Construct the full file path with the refined pattern
file_path_pattern = os.path.join(output_path, sub_dir, filename_pattern)
# Use glob to find the file and ensure it exists
file_list = glob.glob(file_path_pattern)
if file_list:
file_path = file_list[0] # Get the single file path directly
# Load the data from the file
with open(file_path, "rb") as file:
ifgs = pickle.load(file)
else:
raise FileNotFoundError(
f"No file matching '{filename_pattern}' was found in '{os.path.join(output_dir, sub_dir)}'."
)
###################### Read coh:
print("\nReading all coherence data...")
# Define the path components
sub_dir = "Data"
filename_pattern = "All_coh_*" # Pattern to match files starting with "All_ifgs"
# Construct the full file path with the refined pattern
file_path_pattern = os.path.join(output_path, sub_dir, filename_pattern)
# Use glob to find the file and ensure it exists
file_list = glob.glob(file_path_pattern)
if file_list:
file_path = file_list[0] # Get the single file path directly
# Load the data from the file
with open(file_path, "rb") as file:
coh = pickle.load(file)
else:
raise FileNotFoundError(
f"No file matching '{filename_pattern}' was found in '{os.path.join(output_dir, sub_dir)}'."
)
print("\nReading data completed.")
######## stacking all the ifgs 6/12/18 in a numpy var all_ifgs
desired_categories = desired_lengths
print('stacking all the ifgs 6/12/18 in a numpy var all_ifgs')
all_ifgs, all_coh, existing_ifgs_index = read_orig_ifgs_coh(
ifgs, coh, desired_categories
)
print('stacking completed')
del ifgs, coh
gc.collect()
print('ifgs coh deleted')
##### Reading the estimated bias terms as well as the indices of unknowns that can be corrected obtained in step 03 ##############
##############################################################################################
print("Correcting the interferograms...")
# Define the path components
sub_dir = "Data"
filename_pattern_X = "X_base_ifgs_biases.npy" # Pattern to match files starting with "X_base"
filename_pattern_indices = "indices*"
# Construct the full file path with the refined pattern
file_path_pattern_X = os.path.join(output_path, sub_dir, filename_pattern_X)
file_path_pattern_indices = os.path.join(output_path, sub_dir, filename_pattern_indices)
# Use glob to find the file and ensure it exists
file_list = glob.glob(file_path_pattern_X)
if file_list:
file_path = file_list[0] # string path to .npy file
X = np.load(file_path, mmap_mode="r") # ✅ correct way
else:
raise FileNotFoundError(f"No file matching '{filename_pattern_X}' was found in '{os.path.join(output_path, sub_dir)}'.")
# Use glob to find the file and ensure it exists
file_list = glob.glob(file_path_pattern_indices)
if file_list:
file_path = file_list[0] # Get the single file path directly
# Load the data from the file
with open(file_path, "rb") as file:
indices_unknown_tobe_corrected = np.load(file)
else:
raise FileNotFoundError(
f"No file matching '{filename_pattern}' was found in '{os.path.join(output_dir, sub_dir)}'."
)
#### loading indices of unknown that can be corrected and the estimated unknowns
indices_unknown_tobe_corrected_orig = indices_unknown_tobe_corrected.copy()
len_6_biases = indices_unknown_tobe_corrected[-1] + 1 # number of 6-day biases
all_column_indices = np.array(
range(len_6_biases)
) # generating all indices in case we want to esimate all 6-day biases with smoothing constraints.
indices_unknown_tobe_corrected = all_column_indices # in this case we had provided the corrections for all 6-day biases
# extending the indices_unknown_tobe_corrected in the original approach to have the indices of 12/18 correctable ifgs:
extended_indices = (
indices_unknown_tobe_corrected.copy()
) # because in this case indices_unknown_tobe_corrected referes to all_column_indices
X_extended = (
X.copy()
) # because in this case we have estimated all 6-day biases but we don't need them for the correction. we just need them to correct the existing 12/18 days based on the 6 days
extended_indices = extended_indices.tolist()
X_extended = X_extended.tolist()
print('indices loaded')
# Generalized loop to handle any max_con
for n in range(2, max_con + 1): # Start from 2*interval and go up to (max_con)*interval
print('n is ', n)
current_length = n * interval # Calculate the length (e.g., 12, 18, 24, ...)
if current_length in desired_lengths: # Check if this length is required
for i in range(len(indices_unknown_tobe_corrected) - (n - 1)):
last_item = extended_indices[-1] # Get the last index
extended_indices.append(last_item + 1) # Append the new index
# Sum up X values for the current length (n)
# X_sum = sum(
# X[i + j, :, :] for j in range(n)
# ) # Sum over n consecutive indices
X_sum = X[i : i + n].sum(axis=0) # more efficient
# Append the result to X_extended using the corresponding an_values
X_extended.append(
an_values[n - 2] # an_values is 0-based, so use n-2
* np.angle(np.exp(complex(0 + 1j) * X_sum))
)
X = np.array(X_extended)
indices_unknown_tobe_corrected = extended_indices
del X_extended
print('X extended')
#### correcting the ifgs (6/12/18) ########################
#################################################################
####### v3
def wrap_to_pi_inplace(arr):
np.remainder(arr + np.pi, 2*np.pi, out=arr)
arr -= np.pi
return arr
print(f"all_ifgs.shape: {all_ifgs.shape}")
print(f"len(indices_unknown_tobe_corrected): {len(indices_unknown_tobe_corrected)}")
print(f"len(X): {len(X)}")
all_ifgs_cor = np.full(all_ifgs.shape, np.nan, dtype=np.float32)
if uncor_only == 0: # if we want to use the corrected ifgs (using wrapped phases)
batch_size = 1 # adjust based on memory
for i in range(0, len(indices_unknown_tobe_corrected), batch_size):
print('batch ', i)
idx = indices_unknown_tobe_corrected[i:i+batch_size]
arr = all_ifgs[idx] - X[i:i+batch_size]
wrap_to_pi_inplace(arr)
all_ifgs_cor[idx] = arr
else:
print("uncor_only = 1 → skipping correction, copying originals")
all_ifgs_cor[indices_unknown_tobe_corrected] = all_ifgs[indices_unknown_tobe_corrected]
################## v2
#def wrap_to_pi(x):
# """Wrap values to [-pi, pi)."""
# return (x + np.pi) % (2 * np.pi) - np.pi
#
## Preallocate directly as float array filled with NaN
#all_ifgs_cor = np.full(all_ifgs.shape, np.nan, dtype=np.float32)
#
#if uncor_only == 0: # use corrected ifgs (wrapped phases)
# print('uncor_only 0')
# all_ifgs_cor[indices_unknown_tobe_corrected] = wrap_to_pi(all_ifgs[indices_unknown_tobe_corrected] - X)
#else: # no correction, just copy
# all_ifgs_cor[indices_unknown_tobe_corrected] = all_ifgs[indices_unknown_tobe_corrected]
############### # v1
# this was less efficient and so I replaced it with above
#all_ifgs_cor = np.full_like(all_ifgs, None)
#all_ifgs_cor[:, :, :] = np.nan
#
#if uncor_only == 0: # if we want to use the corrected ifgs (using wrapped phases)
# all_ifgs_cor[indices_unknown_tobe_corrected, :, :] = np.angle(
# np.exp(
# complex(0 + 1j)
# * (all_ifgs[indices_unknown_tobe_corrected, :, :] - X[:, :, :])
# )
# )
#else: # no need for correction
# all_ifgs_cor[indices_unknown_tobe_corrected, :, :] = all_ifgs[
# indices_unknown_tobe_corrected, :, :
# ]
#
print ('before outputting')
### Outputting to disk ################
#############################################################################
# Create the directory (and parent directories) if they don't exist
GEOC_dir = "GEOC"
metadata_dir = "metadata"
output_wrap_dir = os.path.join(output_path, GEOC_dir)
os.makedirs(
output_wrap_dir, exist_ok=True
) # create the GEOC directory if it doesn't exist
template_tif_path = os.path.join(root_directory, metadata_dir, frame + ".geo.hgt.tif")
print('template_tif_path', template_tif_path)
if nlook != 1:
resampled_tif_path = os.path.join(output_wrap_dir, frame + ".geo.hgt.tif")
print('template_tif_path', template_tif_path)
print('resampled_tif_path', resampled_tif_path)
print('nlook ', nlook)
resample_geotiff(template_tif_path, resampled_tif_path, nlook)
template_tif_path = resampled_tif_path
print('resample complete')
total_files = len(all_ifgs) # Total number of interferograms
processed_files = 0 # Counter for processed files
print(f"Writing the corrected interferograms to {output_wrap_dir}")
print("Progress: [", end="", flush=True)
time.sleep(3)
for i in range(len(all_ifgs)):
if i in indices_unknown_tobe_corrected:
# Writing progress bar
processed_files += 1
percentage = (processed_files / total_files) * 100
if processed_files % (total_files // 100) == 0: # Update progress every 1%
sys.stdout.write(
f"\rProgress: ["
+ "=" * (int(percentage) // 2)
+ " " * (50 - int(percentage) // 2)
+ f"] {int(percentage)}%"
)
sys.stdout.flush()
inpha = all_ifgs_cor[i, :, :] # your phase input, float32
incoh = all_coh[i, :, :] # your coh input. It can be either 0-255 or 0-1
output_phase_path = os.path.join(output_wrap_dir, all_ifgs_string[i])
output_cc_path = os.path.join(output_wrap_dir, all_ifgs_string[i])
# output_phase_path = output_wrap_dir + all_ifgs_string[i]
# output_cc_path = output_wrap_dir + all_ifgs_string[i]
os.makedirs(output_phase_path, exist_ok=True)
os.makedirs(output_cc_path, exist_ok=True)
output_phase_file = (
output_phase_path + "/" + all_ifgs_string[i] + ".geo.diff_pha.tif"
)
output_cc_file = output_cc_path + "/" + all_ifgs_string[i] + ".geo.cc.tif"
ifg_cc_2tif(inpha, output_phase_file, template_tif_path)
ifg_cc_2tif(incoh, output_cc_file, template_tif_path)
print("\nAll corrected interferograms have been written to disk.")
@@ -0,0 +1,39 @@
# InSAR Phase Bias Correction
This repository contains scripts for mitigating phase bias in InSAR data. It includes tools for reading data, calculating loop closures, estimating calibration parameters, performing inversion, and correcting interferograms.
## Directory Structure
- `PhaseBias_01_Read_Data.py`: Reads input wrapped ifgs and coherence data.
- `PhaseBias_02_Loop_Closures.py`: Calculates loop closures.
- `PhaseBias_03_calibration_pars.py`: Estimates the calibration parameters $a_n$.
- `PhaseBias_04_Inversion.py`: Performs inversion for phase bias estimation.
- `PhaseBias_05_Correction.py`: Corrects interferograms using estimated biases.
- `bin/`: Contains auxiliary functions used by the scripts.
- `config.txt`: Configuration file for setting parameters.
## Usage
1. Clone the repository:
```bash
git clone https://github.com/YourUsername/InSAR_PhaseBias_Correction.git
cd InSAR_PhaseBias_Correction
## Test Dataset
The test dataset used in this repository originates from one of the islands in the Azores. The full dataset can be accessed through the COMET LiCSAR frame **082D_05125_020000**, available at the following link:
[https://gws-access.jasmin.ac.uk/public/nceo_geohazards/LiCSAR_products/82/082D_05125_020000/](https://gws-access.jasmin.ac.uk/public/nceo_geohazards/LiCSAR_products/82/082D_05125_020000/)
Additionally, we provide a **sample dataset**, including example interferograms, which can be downloaded from Zenodo:
[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.14525360.svg)](https://doi.org/10.5281/zenodo.14525360)
# Citation
If you use this repository for your research, please cite the following paper:
Maghsoudi, Y., Hooper, A.J., Wright, T.J., Lazecky, M., & Ansari, H. (2022). Characterizing and correcting phase biases in short-term, multilooked interferograms. Remote Sensing of Environment, 275, 113022.
https://doi.org/10.1016/j.rse.2022.113022
# Acknowledgment
This work was funded by the European Space Agency (ESA) as part of the Phase Bias Correction Project. We gratefully acknowledge their support.
@@ -0,0 +1,583 @@
#!/usr/bin/env python3
import os
import re
from datetime import datetime, timedelta
import numpy as np
from osgeo import gdal
from bin.multilook_w import multilook_w
import configparser
import sys
import warnings
import pickle
import glob
warnings.filterwarnings("ignore", category=np.VisibleDeprecationWarning)
#######################################################################
HELP_TEXT = """
PhaseBias_01_Read_Data.py
This script automates the process of downloading GeoTIFF files for wrapped interferograms and coherence images.
The files can be retrieved either from the COMET-LiCS web portal or from a root path specified in the configuration file.
Assumptions:
- Interferograms are organized in folders named as `yyyymmdd_yyyymmdd` (e.g., `20230101_20230107`).
Files Downloaded:
1. `yyyymmdd_yyyymmdd.geo.diff_pha.tif`:
- Contains the wrapped phase image in radians.
- Values range from -3.14 to 3.14.
2. `yyyymmdd_yyyymmdd.geo.cc.tif`:
- Contains the coherence image of the interferometric pair.
- Values range from 0 to 255, where:
- 0 represents the lowest coherence.
- 255 represents the highest coherence.
Outputs:
1. `All_ifgs_start_end` (Pickle file, saved as `.pkl`):
- A dictionary containing all interferograms available between the specified start and end dates.
2. `All_coh_start_end` (Pickle file, saved as `.pkl`):
- A dictionary containing all coherence data available between the specified start and end dates.
Storage Information:
- All output files are saved in the directory `Data/` under the `output_path` defined in the configuration file.
Additional Output:
- A summary report is generated that includes:
- The number of available interferograms for each temporal baseline.
- The number of missing interferograms.
"""
if "--help" in sys.argv:
print(HELP_TEXT)
sys.exit(0)
###################
# Config file path
config_file = "config.txt"
# Check if config file exists
if not os.path.exists(config_file):
raise FileNotFoundError(
f"Error: The configuration file '{config_file}' was not found in the script's directory."
)
# Initialize the configparser
config = configparser.ConfigParser()
# Read the config.txt file
config.read(config_file)
# Define required parameters
required_parameters = [
"root_path",
"frame",
"start",
"end",
"interval",
"nlook",
"LiCSAR_data",
]
# Initialize a dictionary to store parameters
parameters = {}
# Attempt to retrieve each parameter and catch errors
try:
parameters["root_path"] = config.get("DEFAULT", "root_path")
parameters["output_path"] = config.get("DEFAULT", "output_path")
parameters["frame"] = config.get("DEFAULT", "frame")
parameters["start"] = config.get("DEFAULT", "start")
parameters["end"] = config.get("DEFAULT", "end")
parameters["interval"] = config.getint("DEFAULT", "interval")
parameters["nlook"] = config.getint(
"DEFAULT", "nlook") # Assuming 'nlook' should be an integer
parameters["LiCSAR_data"] = config.get("DEFAULT", "LiCSAR_data")
except configparser.NoOptionError as e:
# Error message if a required parameter is missing
missing_param = str(e).split(": ")[1]
raise ValueError(
f"Error: Required parameter '{missing_param}' is missing in '{config_file}'. Please check the file contents."
)
except configparser.Error as e:
# General error for any configparser-related issues
raise ValueError(f"Error while reading '{config_file}': {e}")
# Assign to individual variables for easy access
root_path = parameters["root_path"]
output_path = parameters["output_path"]
frame = parameters["frame"]
start = parameters["start"]
end = parameters["end"]
interval = parameters["interval"]
nlook = parameters["nlook"]
LiCSAR_data = parameters["LiCSAR_data"]
# hardcoded parameters, not included in the config file
landmask = 1
filtered_ifgs = "yes"
min_baseline = 5
max_baseline = 366
# Print the values to confirm they're being read correctly
print("Root Path:", root_path)
print("output Path:", output_path)
print("Frame:", frame)
print("Start Date:", start)
print("End Date:", end)
print("Interval:", interval)
print("nlook:", nlook)
print("LiCSAR_data", LiCSAR_data)
################
# all_ifgs = read_ifgs(frame, start, end, min_baseline, max_baseline, landmask, nlook, interval, LiCSAR_data, filtered_ifgs)
def read_ifgs(
start,
end,
min_baseline,
max_baseline,
landmask,
nlook,
interval,
LiCSAR_data,
filtered_ifgs,
):
start_date = datetime.strptime(start, "%Y%m%d")
end_date = datetime.strptime(end, "%Y%m%d")
# Check if the file ends with "geo.diff_pha.tif"
# if filename.endswith("geo.diff_unfiltered_pha.tif"): # if unfiltered data are used
if filtered_ifgs == "yes": # yes for the filtered ifgs, no for the unfiltered ifgs
req_file_name = "geo.diff_pha.tif"
else:
req_file_name = "geo.diff_unfiltered_pha.tif"
############ reading
if LiCSAR_data == "yes":
track = frame[0:3] # extracting track number from frame id
if track[0] == "0":
track = track[1:3]
if track[0] == "0":
track = track[1:2]
root_directory = f"/gws/nopw/j04/nceo_geohazards_vol1/public/LiCSAR_products/{track}/{frame}/interferograms/"
else:
root_directory = os.path.join(
root_path, "interferograms"
) # Use os.path.join for consistent path construction
##### Count total files matching the criteria for accurate progress calculation
print(f"Reading data from the path: {root_directory}")
total_files = sum(1 for dirpath, _, filenames in os.walk(root_directory)
for filename in filenames
if filename.endswith(req_file_name))
processed_files = 0
print("Reading wrapped interferograms: [", end="", flush=True)
#####
# Initialize an empty dictionary to store the arrays for each category
category_arrays = {}
last_date = {}
n = 0
if landmask is not None:
if LiCSAR_data == "yes":
landmask_path = f"/gws/nopw/j04/nceo_geohazards_vol1/public/LiCSAR_products/{track}/{frame}/metadata/{frame}.geo.landmask.tif"
else:
# Use glob to find the file ending with ".geo.landmask.tif" in the metadata directory
metadata_dir = os.path.join(root_path, "metadata")
landmask_files = glob.glob(
os.path.join(metadata_dir, "*.geo.landmask.tif"))
if landmask_files:
landmask_path = landmask_files[0] # Take the first match
else:
raise FileNotFoundError(
"No file ending with '.geo.landmask.tif' found in the metadata directory."
)
# Load the landmask file
landmask_dataset = gdal.Open(landmask_path)
landmask_image = landmask_dataset.ReadAsArray()
array_landmask = np.array(landmask_image)
n = 1
# Traverse the root directory and its subdirectories
for dirpath, dirnames, filenames in os.walk(root_directory):
dirnames.sort(
) # This ensures dirnames are processed in alphabetical order
# Iterate through the files in the current directory
for filename in filenames:
# Check if the file ends with "geo.diff_pha.tif"
# if filename.endswith("geo.diff_unfiltered_pha.tif"): # if unfiltered data are used
if (filtered_ifgs == "yes"
): # yes for the filtered ifgs, no for the unfiltered ifgs
req_file_name = "geo.diff_pha.tif"
else:
req_file_name = "geo.diff_unfiltered_pha.tif"
if filename.endswith(req_file_name):
file_path = os.path.join(dirpath, filename)
#### for printing into the console
processed_files += 1
percentage = (processed_files / total_files) * 100
# Clear previous percentage and print updated one
sys.stdout.write(
"\rReading wrapped phases: [{:<50}] {}%".format(
"=" * int(percentage // 2), int(percentage)))
sys.stdout.flush()
#####
# Extract the dates from the file name
match = re.search(r"(\d+)_(\d+)", filename)
if match:
date1 = match.group(1)
date2 = match.group(2)
# Convert the dates to datetime objects
date1_obj = datetime.strptime(date1, "%Y%m%d")
date2_obj = datetime.strptime(date2, "%Y%m%d")
# Check if the dates fall within the specified range
category = (date2_obj - date1_obj).days
if (start_date <= date1_obj <= end_date
and start_date <= date2_obj <= end_date
and category < max_baseline
and category > min_baseline):
if (
n == 1
): # finding the first and last acquisiton in the time-series
first_acq = date1_obj
else:
last_acq = date2_obj
n = n + 1
# Calculate the difference in days between the two dates
# Open the TIFF file
tiff_dataset = gdal.Open(file_path)
# Read the image data as a NumPy array
tiff_image = tiff_dataset.ReadAsArray()
# Convert the image to a numpy array
array_data = np.array(tiff_image)
array_data[array_data == 0] = (
np.nan
) ## converting the zerso values in wrapped phases into nan. This is helpful when calculating loop closures
if landmask != None:
array_data[array_landmask != 1] = np.nan
if (
nlook != None and nlook != 1
): # incase of unwrap data because they are already multilooked to 10 we don't multilook them here
array_data = multilook_w(array_data, nlook)
if category not in last_date:
last_date[category] = date1_obj
# if (date1_obj - date2_obj) > interval
# appending None to the category_arrays where there are missing ifgs in the middle of time-series
diff_ifgs = (
date1_obj - last_date[category]
).days # /category #difference between the first epochs of two consecutive ifg
if diff_ifgs > interval:
n_no_acq = int(diff_ifgs / interval -
1) ## number of missing ifgs
for i in range(
n_no_acq
): # the number of none depends on the number of missing ifgs
# Append the none to the existing array
category_arrays[category].append(None)
last_date[category] = date1_obj
# Check if the category is already in the dictionary
if category in category_arrays:
# If the category already exists, append the array to the existing array
category_arrays[category].append(array_data)
else:
# If the category doesn't exist, create a new list with the array
category_arrays[category] = [array_data]
# appending None to the category_arrays where there are missing ifgs in the end of time-series
for category in sorted(category_arrays):
while (last_date[category] + timedelta(category)) < last_acq:
category_arrays[category].append(None)
last_date[category] = last_date[category] + timedelta(interval)
# appending None to the category_arrays where there are missing ifgs in the begining of time-series
# max number of expected 6-day(i.e. interval) interferograms in the full time-series
max_ifg_number = abs(int((first_acq - last_acq).days / interval))
# all the categories in the data e.g. 6, 12, 18 etc
cat = []
for category in category_arrays:
cat.append(category)
for i in range(interval, max(cat)+1, interval):
if i in cat:
while len(category_arrays[i]) < (max_ifg_number + 1 - i/interval):
category_arrays[i].insert( 0, None)
print("\nFinished reading all interferograms.")
return category_arrays
###########################################################################################################################
##########################################################################################################################
def read_coh(start, end, min_baseline, max_baseline, nlook, landmask, interval,
LiCSAR_data):
start_date = datetime.strptime(start, "%Y%m%d")
end_date = datetime.strptime(end, "%Y%m%d")
############ reading
if LiCSAR_data == "yes":
track = frame[0:3]
if track[0] == "0":
track = track[1:3]
if track[0] == "0":
track = track[1:2]
root_directory = f"/gws/nopw/j04/nceo_geohazards_vol1/public/LiCSAR_products/{track}/{frame}/interferograms/"
else:
root_directory = os.path.join(
root_path, "interferograms"
) # Use os.path.join for consistent path construction
req_file_name = "geo.cc.tif"
##### Count total files matching the criteria for accurate progress calculation
total_files = sum(1 for dirpath, _, filenames in os.walk(root_directory)
for filename in filenames
if filename.endswith(req_file_name))
processed_files = 0
print("Reading coherence data: [", end="", flush=True)
#####
# Initialize an empty dictionary to store the arrays for each category
category_arrays = {}
last_date = {}
n = 0
if landmask is not None:
if LiCSAR_data == "yes":
landmask_path = f"/gws/nopw/j04/nceo_geohazards_vol1/public/LiCSAR_products/{track}/{frame}/metadata/{frame}.geo.landmask.tif"
else:
# Use glob to find the file ending with ".geo.landmask.tif" in the metadata directory
metadata_dir = os.path.join(root_path, "metadata")
landmask_files = glob.glob(
os.path.join(metadata_dir, "*.geo.landmask.tif"))
if landmask_files:
landmask_path = landmask_files[0] # Take the first match
else:
raise FileNotFoundError(
"No file ending with '.geo.landmask.tif' found in the metadata directory."
)
# Load the landmask file
landmask_dataset = gdal.Open(landmask_path)
landmask_image = landmask_dataset.ReadAsArray()
array_landmask = np.array(landmask_image)
n = 1
# Traverse the root directory and its subdirectories
for dirpath, dirnames, filenames in os.walk(root_directory):
# Iterate through the files in the current directory
for filename in filenames:
# Check if the file ends with "geo.diff_pha.tif"
if filename.endswith(req_file_name):
file_path = os.path.join(dirpath, filename)
#### for printing into the console
processed_files += 1
percentage = (processed_files / total_files) * 100
# Clear previous percentage and print updated one
sys.stdout.write(
"\rReading coherence data: [{:<50}] {}%".format(
"=" * int(percentage // 2), int(percentage)))
sys.stdout.flush()
#####
# Extract the dates from the file name
match = re.search(r"(\d+)_(\d+)", filename)
if match:
date1 = match.group(1)
date2 = match.group(2)
# Convert the dates to datetime objects
date1_obj = datetime.strptime(date1, "%Y%m%d")
date2_obj = datetime.strptime(date2, "%Y%m%d")
# Check if the dates fall within the specified range
category = (date2_obj - date1_obj).days
if (start_date <= date1_obj <= end_date
and start_date <= date2_obj <= end_date
and category < max_baseline
and category > min_baseline):
if (
n == 1
): # finding the first and last acquisiton in the time-series
first_acq = date1_obj
else:
last_acq = date2_obj
n = n + 1
# Calculate the difference in days between the two dates
# Open the TIFF file
tiff_dataset = gdal.Open(file_path)
# Read the image data as a NumPy array
tiff_image = tiff_dataset.ReadAsArray()
# Convert the image to a numpy array
array_data = np.array(tiff_image)
# Convert array_data to a float type that can accommodate np.nan
array_data = array_data.astype(np.float32)
if landmask != 0:
array_data[array_landmask != 1] = np.nan
if (
nlook != None and nlook != 1
): # incase of unwrap data because they are already multilooked to 10 we don't multilook them here
array_data = multilook(array_data, nlook)
if category not in last_date:
last_date[category] = date1_obj
# if (date1_obj - date2_obj) > interval
# appending None to the category_arrays where there are missing ifgs in the middle of time-series
diff_ifgs = (
date1_obj - last_date[category]
).days # /category #difference between the first epochs of two consecutive ifg
if diff_ifgs > interval:
n_no_acq = int(diff_ifgs / interval -
1) ## number of missing ifgs
for i in range(
n_no_acq
): # the number of none depends on the number of missing ifgs
# Append the none to the existing array
category_arrays[category].append(None)
last_date[category] = date1_obj
# Check if the category is already in the dictionary
if category in category_arrays:
# If the category already exists, append the array to the existing array
category_arrays[category].append(array_data)
else:
# If the category doesn't exist, create a new list with the array
category_arrays[category] = [array_data]
# appending None to the category_arrays where there are missing ifgs in the end of time-series
for category in sorted(category_arrays):
while (last_date[category] + timedelta(category)) < last_acq:
category_arrays[category].append(None)
last_date[category] = last_date[category] + timedelta(interval)
# appending None to the category_arrays where there are missing ifgs in the begining of time-series
# max number of expected 6-day(i.e. interval) interferograms in the full time-series
max_ifg_number = abs(int((first_acq - last_acq).days / interval))
# all the categories in the data e.g. 6, 12, 18 etc
cat = []
for category in category_arrays:
cat.append(category)
for i in range(interval, max(cat)+1, interval):
if i in cat:
while len(category_arrays[i]) < (max_ifg_number + 1 - i/interval):
category_arrays[i].insert(0, None)
print("\nFinished reading all coherence data.")
return category_arrays
##########################################################################################################################
##########################################################################################################################
all_ifgs = read_ifgs(
start,
end,
min_baseline,
max_baseline,
landmask,
nlook,
interval,
LiCSAR_data,
filtered_ifgs,
)
# Define the directory path
directory_path = os.path.join(output_path, "Data")
# Create the directory if it doesn't exist
os.makedirs(directory_path, exist_ok=True)
# Define the file path
#file_path = os.path.join(directory_path, f"_all_ifgs_{start}_{end}")
# Remove all files inside the directory
if os.path.exists(directory_path):
files = glob.glob(os.path.join(directory_path, "*"))
for file in files:
os.remove(file)
# for writing the all_loops
file_path = output_path + "/Data/" + "All_ifgs_" + start + "_" + end + ".pkl"
with open(file_path, "wb") as file: # for writting a dictionary to a file
pickle.dump(all_ifgs, file)
# Free memory before starting coherence
import gc
del all_ifgs
gc.collect()
################################################################
all_coh = read_coh(start, end, min_baseline, max_baseline, landmask, nlook,
interval, LiCSAR_data)
## for writting the all_coh
file_path = output_path + "/Data/" + "All_coh_" + start + "_" + end + ".pkl"
with open(file_path, "wb") as file: # for writting a dictionary to a file
pickle.dump(all_coh, file)
################################################
# After processing all interferograms, generate the report
print("\nReport on the number of IFGs and missing IFGs per category:")
for category in sorted(all_ifgs):
num_ifgs = sum(1 for item in all_ifgs[category]
if item is not None) # Count valid IFGs
num_missing_ifgs = sum(1 for item in all_ifgs[category]
if item is None) # Count missing IFGs
print(
f"{category}-days: Number of IFGs: {num_ifgs} Number of missing IFGs: {num_missing_ifgs}"
)
@@ -0,0 +1,310 @@
#!/usr/bin/env python3
import numpy as np
import pickle
import glob
import configparser
import os
import sys
import warnings
warnings.filterwarnings("ignore", category=np.VisibleDeprecationWarning)
################################################################################################
HELP_TEXT = """
PhaseBias_02_Loop_Closures.py
This script calculates loop closures (Δφ) using the interferograms imported in the first step.
Definition of Loop Closures:
Loop closures, Δφ, are calculated for the epochs between `i` and `k`, and are defined as:
Δφ_(i,k) = |φ_(i,k) - ∑_(t=i)^k φ_(t,t+1)|_2π
Where:
- φ_(i,j): Represents the phase difference for a pixel in the interferogram formed between epochs `i` and `j`.
- |.|_2π: Indicates that the result is wrapped modulo 2π (i.e., values range from -π to π).
Key Information:
- Nonzero closure phase is a by-product of spatial filtering/multilooking and is primarily associated with changes in the scattering and electrical properties of the ground surface.
- The calculated loop closures are based on the minimum temporal-baseline interferograms defined in the configuration file (parameter: `interval`) and are referred to as base interferograms. These may represent:
- 12- and 6-day closures (or 24- and 12-day closures), Δφ_(i,i+2)
- 18- and 6-day closures (or 36- and 12-day closures), Δφ_(i,i+3)
The distinction depends on whether the base interferograms are 6-day or 12-day intervals.
Outputs:
- The calculated loop closures are stored as a dictionary in a file named:
`All_loops_start_end.pkl`
- The output is saved in the directory `Data/` under the `output_path` defined in the configuration file.
Loop Closure Report:
At the end of the script, a loop closure report is displayed. This report includes:
- The number of generated and missing loop closures for short-interval closures, such as 12-6 and 18-6.
- The number of generated and missing long-interval closures, obtained using long-term interferograms, such as 204-6 and 204-12.
Usage:
1. Ensure the interferograms from the first script are available.
2. Run the script to generate loop closures for the specified temporal baselines.
Example:
```bash
python PhaseBias_02_Loop_Closures.py
"""
if "--help" in sys.argv:
print(HELP_TEXT)
sys.exit(0)
################################################################################################
# Config file path
config_file = "config.txt"
# Check if config file exists
if not os.path.exists(config_file):
raise FileNotFoundError(
f"Error: The configuration file '{config_file}' was not found in the script's directory."
)
# Initialize the configparser
config = configparser.ConfigParser()
# Read the config.txt file
config.read(config_file)
# Define required parameters
required_parameters = [
"root_path",
"frame",
"start",
"end",
"interval",
"nlook",
"LiCSAR_data",
]
# Initialize a dictionary to store parameters
parameters = {}
# Attempt to retrieve each parameter and catch errors
try:
parameters["root_path"] = config.get("DEFAULT", "root_path")
parameters["output_path"] = config.get("DEFAULT", "output_path")
parameters["frame"] = config.get("DEFAULT", "frame")
parameters["start"] = config.get("DEFAULT", "start")
parameters["end"] = config.get("DEFAULT", "end")
parameters["interval"] = config.getint("DEFAULT", "interval")
parameters["nlook"] = config.getint(
"DEFAULT", "nlook") # Assuming 'nlook' should be an integer
parameters["LiCSAR_data"] = config.get("DEFAULT", "LiCSAR_data")
except configparser.NoOptionError as e:
# Error message if a required parameter is missing
missing_param = str(e).split(": ")[1]
raise ValueError(
f"Error: Required parameter '{missing_param}' is missing in '{config_file}'. Please check the file contents."
)
except configparser.Error as e:
# General error for any configparser-related issues
raise ValueError(f"Error while reading '{config_file}': {e}")
# Assign to individual variables for easy access
root_path = parameters["root_path"]
output_path = parameters["output_path"]
frame = parameters["frame"]
start = parameters["start"]
end = parameters["end"]
interval = parameters["interval"]
nlook = parameters["nlook"]
LiCSAR_data = parameters["LiCSAR_data"]
# hardcoded parameters, not included in the config file
landmask = 1
filtered_ifgs = "yes"
max_loop = 5 # in case of 3 all loops with 6,12,18-day will be calculated (e.g. (60,6), (60,12) and (60,18))
#############################################################################################
#################################################################################################
def loop_calc(max_loop):
## Read ifgs:
# Define the path components
sub_dir = "Data"
filename_pattern = "All_ifgs_*" # Pattern to match files starting with "All_ifgs"
# Construct the full file path with the refined pattern
file_path_pattern = os.path.join(output_path, sub_dir, filename_pattern)
# Use glob to find the file and ensure it exists
file_list = glob.glob(file_path_pattern)
if file_list:
file_path = file_list[0] # Get the single file path directly
# Load the data from the file
with open(file_path, "rb") as file:
all_ifgs = pickle.load(file)
else:
raise FileNotFoundError(
f"No file matching '{filename_pattern}' was found in '{os.path.join(output_dir, sub_dir)}'."
)
loop = {}
missing = {}
cat = sorted(all_ifgs.keys()) # Get sorted categories
# print('cat = ', cat)
# Initialize counters for reporting
loop_counts = {
category: {
cat[l]: 0
for l in range(max_loop)
}
for category in sorted(all_ifgs.keys())
}
missing_counts = {
category: {
cat[l]: 0
for l in range(max_loop)
}
for category in sorted(all_ifgs.keys())
}
for category in cat:
loop[category] = {
} # Initialize the key in the loop dictionary with an inner dictionary
missing[category] = [] # second ver
for l in range(
max_loop
): # it was up to 3 in the first version. but this allows to go for longer loops e.g. 288-72 (cat[11] is 72)
loop[category][cat[l]] = [
] # Initialize the key in the inner dictionary
# missing[cat[l]] = [] # first ver
# Calculate total iterations for progress percentage
total_iterations = sum(
len(all_ifgs[cat[i]]) for l in range(max_loop)
for i in range(1, len(cat))
if cat[i] % cat[l] == 0 and cat[i] != cat[l])
completed_iterations = 0
# Display the message before starting the progress bar
print(
f"Calculating all {interval}, {2 * interval}, and {3 * interval} loop closures."
)
for l in range(
0, max_loop
): # l could be 6, 12 and 18 to calculate e.g. 36-6 or 36-12 or 36-18
for i in range(1, len(cat)): # index for the category e.g. 6, 12, 18
if cat[i] % cat[l] == 0 and cat[i] != cat[
l]: # such as 12/6 or 24/12
for t in range(len(all_ifgs[
cat[i]])): # index for the epochs in each category
####################progress bar
completed_iterations += 1
percentage = (completed_iterations /
total_iterations) * 100
# Display progress percentage
sys.stdout.write("\rProgress: [{:<50}] {}%".format(
"=" * int(percentage // 2), int(percentage)))
sys.stdout.flush()
##################################
if cat[l] == interval:
end_index = t + int(cat[i] / cat[l])
# print('end_index = ', end_index)
else:
end_index = t + int(cat[i] / cat[l]) * int(
cat[l] / interval)
# recording the missing ifgs in each cat e.g. 6,12,18
#if np.any(np.array(all_ifgs[cat[i]])[t] == None):
if np.any(np.array(all_ifgs[cat[i]], dtype=object)[t] == None):
missing[cat[i]].append(
t
) # to record the missing ifgs index for each cateogory e.g. 18
for e in range(t, end_index, int(cat[l]/interval)): # to record the missing ifgs index for the period of each loop
elem = all_ifgs[cat[l]][e]
if elem is None:
missing[cat[l]].append(e)
if all_ifgs[cat[i]][t] is None or any(all_ifgs[cat[l]][elem] is None for elem in range(t, end_index, int(cat[l] / interval))):
loop[cat[i]][cat[l]].append(None)
missing_counts[cat[i]][cat[l]] += 1 # Increment missing loop counter
else:
closure = np.angle( np.exp( 1j * ( np.array(all_ifgs[cat[i]][t], dtype=np.float32)- np.sum( np.array(all_ifgs[cat[l]][t:end_index:int(cat[l] / interval)], dtype=np.float32), axis=0))))
if cat[i] in loop:
loop[cat[i]][cat[l]].append(closure)
loop_counts[cat[i]][cat[
l]] += 1 # Increment successful loop counter
else:
loop[cat[i]][cat[l]] = [closure]
print("\n Finished calculating the loop closures.")
# Generate report
print("\n=== Loop Closure Report ===")
for category in [
2 * interval,
3 * interval,
]: # Restrict to relevant categories e.g. 18-6 and 12-6 as the main observations
for l in [interval]: # Restrict to the loop levels of interest
if category in loop_counts and l in loop_counts[category]:
generated = loop_counts[category].get(l, 0)
missing = missing_counts[category].get(l, 0)
print(
f"Loop Closure {category} - {l}: Generated = {generated}, Missing = {missing}"
)
print("\n=== Loop Closure Report for Long-interval Loop Closures ===")
# Iterate over categories greater than 200
for category in cat:
if category > 200: # Check for long categories
for l in range(
1,
5 * interval): # Check loop levels less than 5 * interval
if category in loop_counts and l in loop_counts[category]:
generated = loop_counts[category].get(l, 0)
if generated >= 1: # Only report if at least one loop is generated
print(
f"Loop Closure {category} - {l}: Generated = {generated}"
)
return loop, missing
################################################################################################
all_loops, missing = loop_calc(max_loop)
# Define the directory path
directory_path = os.path.join(output_path, "Data")
# Create the directory if it doesn't exist
os.makedirs(directory_path, exist_ok=True)
# Define the file path
file_path = os.path.join(directory_path, f"All_loops_{start}_{end}.pkl")
with open(file_path, "wb") as file: # for writting a dictionary to a file
pickle.dump(all_loops, file)
###
# Define the file path
file_path = os.path.join(directory_path, f"missing_loops")
with open(file_path, "wb") as file: # for writting a dictionary to a file
pickle.dump(missing, file)
@@ -0,0 +1,424 @@
#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
import pickle
import os
import sys
import glob
import configparser
import warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=np.VisibleDeprecationWarning)
################################################################################
HELP_TEXT = """
PhaseBias_03_calibration_pars.py
This script estimates the calibration parameters a_n using the loop closures calculated in the previous step.
The calibration parameters a_n are estimated by calculating the ratio of the long-term loop closure for the interferogram of interest to the long-term loop closure for the base interferogram. Assuming negligible bias in long-term interferograms, a_n is calculated as follows:
a_n = |φ(i,i+l) - Σ(t=i to i+l)φ(t,t+1+n)|_2π / |φ(i,i+l) - Σ(t=i to i+l)φ(t,t+1)|_2π
where:
- φ(i,i+l) is a long-term interferogram connecting epoch i to i+l.
- φ(t,t+1) represents the base interferogram.
- φ(t,t+1+n) is the short interferogram to be corrected using a_n.
### Input:
1. Loop closures from the previous step (e.g., 216-6, 216-12, and 216-18 for 6-day acquisition intervals).
2. The long-term interferogram length (e.g., 216 days) must be specified at the beginning.
3. The number of a_n parameters to estimate, specified using `num_a`. For example:
- Setting `num_a=2` indicates that a1 and a2 will be estimated (used to correct 12- and 18-day interferograms).
- For correcting longer interferograms, `num_a` should be set accordingly.
### Output:
1. All possible a_n values are calculated.
2. Visualizations:
- Example plots of a_n arrays and their corresponding histograms, illustrating spatial variations.
- Time-series plots showing how a_n values evolve over time.
3. Mean a_n values over time are output for further use.
### File Outputs:
- Results are stored in the output directory defined in the `config.txt` file under `/Data/` as `Mean_an_values.pkl`.
### Additional Notes:
- Users should ensure that `num_a` aligns with the desired temporal baselines for correction.
"""
if "--help" in sys.argv:
print(HELP_TEXT)
sys.exit(0)
###############################################################################
# Config file path
config_file = "config.txt"
# Check if config file exists
if not os.path.exists(config_file):
raise FileNotFoundError(
f"Error: The configuration file '{config_file}' was not found in the script's directory."
)
# Initialize the configparser
config = configparser.ConfigParser()
# Read the config.txt file
config.read(config_file)
# Define required parameters
required_parameters = [
"root_path",
"frame",
"start",
"end",
"interval",
"nlook",
"LiCSAR_data",
]
# Initialize a dictionary to store parameters
parameters = {}
# Attempt to retrieve each parameter and catch errors
try:
parameters["root_path"] = config.get("DEFAULT", "root_path")
parameters["output_path"] = config.get("DEFAULT", "output_path")
parameters["frame"] = config.get("DEFAULT", "frame")
parameters["start"] = config.get("DEFAULT", "start")
parameters["end"] = config.get("DEFAULT", "end")
parameters["interval"] = config.getint("DEFAULT", "interval")
parameters["nlook"] = config.getint(
"DEFAULT", "nlook"
) # Assuming 'nlook' should be an integer
parameters["num_a"] = config.getint("DEFAULT", "num_a")
parameters["LiCSAR_data"] = config.get("DEFAULT", "LiCSAR_data")
except configparser.NoOptionError as e:
# Error message if a required parameter is missing
missing_param = str(e).split(": ")[1]
raise ValueError(
f"Error: Required parameter '{missing_param}' is missing in '{config_file}'. Please check the file contents."
)
except configparser.Error as e:
# General error for any configparser-related issues
raise ValueError(f"Error while reading '{config_file}': {e}")
# Assign to individual variables for easy access
root_path = parameters["root_path"]
output_path = parameters["output_path"]
frame = parameters["frame"]
start = parameters["start"]
end = parameters["end"]
interval = parameters["interval"]
nlook = parameters["nlook"]
num_a = parameters["num_a"]
LiCSAR_data = parameters["LiCSAR_data"]
# hardcoded parameters, not included in the config file
landmask = 1
filtered_ifgs = "yes"
max_loop = 5 # in case of 3 all loops with 6,12,18-day will be calculated (e.g. (60,6), (60,12) and (60,18))
##################################################### Loop Closure calculation #####################################################
####################################################################################################################################
track = frame[0:3]
if track[0] == "0":
track = track[1:3]
if track[0] == "0":
track = track[1:2]
###################### Read coh:
print("\nReading all coherence data...")
# Define the path components
sub_dir = "Data"
filename_pattern = "All_coh_*" # Pattern to match files starting with "All_ifgs"
# Construct the full file path with the refined pattern
file_path_pattern = os.path.join(output_path, sub_dir, filename_pattern)
# Use glob to find the file and ensure it exists
file_list = glob.glob(file_path_pattern)
if file_list:
file_path = file_list[0] # Get the single file path directly
# Load the data from the file
with open(file_path, "rb") as file:
coh = pickle.load(file)
else:
raise FileNotFoundError(
f"No file matching '{filename_pattern}' was found in '{os.path.join(output_dir, sub_dir)}'."
)
print("Reading coherence data completed.")
##################### Read Loops
print("\nReading all loop closures...")
filename_pattern = "All_loops_*" # Pattern to match files starting with "All_ifgs"
# Construct the full file path with the refined pattern
file_path_pattern = os.path.join(output_path, sub_dir, filename_pattern)
# Use glob to find the file and ensure it exists
file_list = glob.glob(file_path_pattern)
if file_list:
file_path = file_list[0] # Get the single file path directly
# Load the data from the file
with open(file_path, "rb") as file:
all_loops = pickle.load(file)
else:
raise FileNotFoundError(
f"No file matching '{filename_pattern}' was found in '{os.path.join(output_dir, sub_dir)}'."
)
print("Reading loop closures completed.")
##################################################### Loop Closure calculation #####################################################
####################################################################################################################################
long_baseline = 216 # 36,72,108,144,180,216,252,288,324
coh_thresh = 25
def calc_an(loop_360_n, loop_360_6):
"""
Calculates the a_n values from loop closures.
Parameters:
loop_360_n (ndarray): Array of loop closures for n-day intervals.
loop_360_6 (ndarray): Array of loop closures for 6-day intervals.
Returns:
ndarray: Mean a_n values for all loop closures.
list: List of all a_n arrays for further processing or plotting.
"""
ratios = []
# Loop through indices
for i in range(len(loop_360_6)):
if loop_360_6[i] is not None and loop_360_n[i] is not None:
# Calculate the ratio for non-NaN elements
ratio_i = np.divide(
loop_360_n[i],
loop_360_6[i],
out=np.full_like(loop_360_n[i], np.nan),
where=~np.isnan(loop_360_6[i]),
)
ratios.append(ratio_i)
# Check if `ratios` is empty before proceeding
if not ratios:
print("Warning: No valid a_n values could be calculated. Returning NaN values.")
return np.array([np.nan]), []
# Convert the list of ratios to a numpy array
an = np.array(ratios, dtype=object)
mean_an_long_baseline = []
# Calculate mean values of each a_n
for arr in an:
mask = (arr > 0) & (arr < 1) # Apply mask to filter invalid values
arr[~mask] = np.nan
if not np.isnan(arr).all(): # Check if all elements are NaN
mean_an = np.nanmean(arr)
else:
mean_an = np.nan # Assign NaN for completely empty slices
mean_an_long_baseline.append(mean_an)
return np.array(mean_an_long_baseline), an
##################################################################################
############################
def plot_an(an_arrays, mean_a_long_baseline, k):
"""
Plots the a_n arrays with the largest coverage and their histograms in a two-row layout,
as well as the mean values of calibration parameters a_n over time.
Parameters:
an_arrays (list): List of a_n arrays.
mean_a_long_baseline (ndarray): Array of mean calibration parameter values for a_1, a_2, ..., a_n.
k (int): The current value of k (e.g., 2 for a1, 3 for a2).
"""
# Calculate the coverage (number of non-NaN values) for each array
coverage = []
valid_an_arrays = [] # Store only valid arrays for plotting
for arr in an_arrays:
if (
arr is not None and arr.ndim == 2 and not np.all(np.isnan(arr))
): # Check for valid 2D arrays
coverage.append(np.sum(~np.isnan(arr))) # Count non-NaN values
valid_an_arrays.append(arr)
# Sort arrays by coverage in descending order
sorted_indices = np.argsort(coverage)[::-1]
selected_arrays = [
valid_an_arrays[idx] for idx in sorted_indices[:6]
] # Select top 6 arrays
# Plot the a_n arrays and their histograms in a two-row layout
if selected_arrays:
num_arrays = len(selected_arrays)
fig = plt.figure(figsize=(4 * num_arrays, 8))
gs = GridSpec(
2, num_arrays + 1, width_ratios=[1] * num_arrays + [0.1]
) # Add space for colorbar
# Plot selected arrays
axes_img = []
for i, arr in enumerate(selected_arrays):
ax_img = fig.add_subplot(gs[0, i])
im = ax_img.imshow(arr, cmap="RdYlBu", vmin=-0.8, vmax=0.8)
ax_img.set_title(f"{i+1}th $a_{{{k-1}}}$ Array") # Dynamically set title
ax_img.axis("off")
axes_img.append(ax_img)
# Add a single colorbar for all array plots
cbar_ax = fig.add_subplot(gs[0, -1])
fig.colorbar(im, cax=cbar_ax, orientation="vertical", label="Color Scale")
# Plot histograms for the selected arrays
for i, arr in enumerate(selected_arrays):
ax_hist = fig.add_subplot(gs[1, i])
ax_hist.hist(arr.flatten(), bins=100, color="blue", alpha=0.7, density=True)
ax_hist.set_title(
f"{i+1}th $a_{{{k-1}}}$ Histogram"
) # Dynamically set title
ax_hist.set_xlim([-10, 10]) # Adjust histogram range as needed
plt.tight_layout()
plt.show()
else:
print("No valid a_n arrays available for plotting.")
# Plot the mean values of a_n over time
x_values = np.arange(len(mean_a_long_baseline)) # Sequential indices for x-axis
fig, ax = plt.subplots(figsize=(6, 4))
# Filter out NaN values to avoid gaps in the plot
valid_indices = ~np.isnan(mean_a_long_baseline) # Mask for valid (non-NaN) entries
x_valid = x_values[valid_indices] # Only use valid time steps
y_valid = np.array(mean_a_long_baseline)[valid_indices] # Only use valid a_n values
# Remove NaN values for trendline fitting
valid_indices = ~np.isnan(mean_a_long_baseline) # Mask for valid (non-NaN) entries
if (
valid_indices.sum() > 1
): # Ensure there are at least two valid points for fitting
# x_valid = x_values[valid_indices]
y_valid = np.array(mean_a_long_baseline)[valid_indices]
x_valid = np.arange(len(y_valid))
# Fit and plot a trendline
coefficients = np.polyfit(x_valid, y_valid, 1)
trendline = np.polyval(coefficients, x_valid)
ax.plot(x_valid, trendline, color="red", label="Trendline")
# Scatter plot for all points (including NaN if any)
ax.scatter(
#x_values,
#mean_a_long_baseline,
x_valid, # Only use valid time steps
y_valid, # Only use valid a_n values
color="blue",
marker="o",
label="Mean Values",
s=9,
)
# Set labels and limits
ax.set_ylim(-3, 3) # Adjust limits as needed
ax.set_xlabel("Time Step") # Sequential index as x-axis
ax.set_ylabel("Mean Values", fontsize=12)
ax.legend()
# Adjust layout and show the plot
plt.tight_layout()
plt.show()
##
######### forming 360-6
loop_360_6_all = np.array(all_loops[long_baseline][interval], dtype=object)
coh_360 = np.array(coh[long_baseline][:], dtype=object)
loop_360_6 = np.full_like(
loop_360_6_all, np.nan
) # create a new array as the same size of loop_360_6_all with nan values
for i, arr in enumerate(loop_360_6_all):
if arr is not None:
(frame_row, frame_col) = np.shape(arr)
loop_360_6[i] = np.where((coh_360[i] > coh_thresh), arr, np.nan)
###### forming 360-n (n=12,18,24 etc)
# mean_a_long_baseline = []
final_mean_values = []
an_labels = []
# Loop through the values of k corresponding to the number of calibration parameters
for k in range(2, 2 + num_a): # k=2 for a1, k=3 for a2, etc.
mean_an_long_baseline = []
# Forming 360-n (n=12, 18, 24, etc.)
loop_360_n_all = np.array(all_loops[long_baseline][k * interval], dtype=object)
loop_360_n = np.full_like(loop_360_n_all, np.nan)
for i, arr in enumerate(loop_360_n_all):
if arr is not None:
# Apply coherence threshold filtering
loop_360_n[i] = np.where((coh_360[i] > coh_thresh), arr, np.nan)
# Calculate a_n values
mean_an_long_baseline, an_arrays = calc_an(loop_360_n, loop_360_6)
# If all values in mean_an_long_baseline are nan (empty ratios), stop execution
if np.isnan(mean_an_long_baseline).all():
print("No valid a_n values could be calculated. Stopping execution.")
sys.exit(1) # Exit the script with an error code (1 means failure)
# Calculate the mean of all mean values for this k and store it
overall_mean = np.nanmean(mean_an_long_baseline)
final_mean_values.append(overall_mean)
an_labels.append(f"a{k-1}")
for idx, mean_a in enumerate(mean_an_long_baseline, start=1):
if not np.isnan(mean_a): # Check if the value is not NaN
print(f"Mean of the {idx}th a({k-1}) is {mean_a:.6f}")
plot_an(an_arrays, mean_an_long_baseline, k)
# Print the final mean values across all k
for k_idx, final_mean in enumerate(final_mean_values, start=2):
print(f"Final mean value for a({k_idx-1}) is {final_mean:.6f}")
# Write final mean values to a text file
output_path = os.path.join(parameters["output_path"], "Data")
os.makedirs(output_path, exist_ok=True) # Create directory if it doesn't exist
output_file = os.path.join(output_path, "an.txt")
with open(output_file, "w") as file:
for label, mean_value in zip(an_labels, final_mean_values):
file.write(f"{label}={mean_value:.6f}\n")
print(f"Final mean values written to {output_file}.")
@@ -0,0 +1,673 @@
#!/usr/bin/env python3
import numpy as np
import pickle
import os
from scipy.sparse import csc_array
from scipy.sparse.linalg import lsqr
import sys
import math
from bin.read_orig_ifgs_coh import read_orig_ifgs_coh
from bin.circular_mean_var import circular_mean_and_variance_over_epochs
import glob
import configparser
import warnings
warnings.filterwarnings("ignore", category=np.VisibleDeprecationWarning)
################################################################################
HELP_TEXT = """
PhaseBias_04_Inversion.py
This script estimates the phase bias terms for the base interferograms using short-term closure phases as input.
The bias terms derived in this step serve as the foundation for correcting other short-term interferograms.
### Workflow:
1. **Masking Noisy Loop Closures:**
- A moving average is applied to the time-series of loop closures to account for seasonal fluctuations.
- A circular moving average (mean of complex values over time) is computed for each pixel.
- The distance of each loop closure from the moving average is calculated. If the distance exceeds a threshold (2σ), the point is masked as noisy.
- The circular standard deviation (σ) is computed using the von Mises distribution (circular normal distribution).
2. **Refined Loop Closures:**
- Masked loop closures, denoted as 〖Δφ〗_(i,i+2)^r and 〖Δφ〗_(i,i+3)^r, are used as primary observations for phase bias estimation.
3. **First Inversion (Without Temporal Smoothing Constraints):**
- Estimates the bias terms that can be corrected directly from the observed loop closures.
4. **Second Inversion (With Temporal Smoothing Constraints):**
- Incorporates temporal smoothing constraints to estimate additional bias terms that cannot be directly derived from loop closures.
- The temporal smoothing minimizes differences between bias terms over time, ensuring consistency.
5. **Combining Results:**
- Bias terms from the first inversion are combined with the results of the second inversion to include terms not estimated in the first round.
### Outputs:
- The phase bias terms for the base interferograms are stored as a NumPy array file:
- `X_base_ifgs_biases.npy`, saved in the `Data` directory under the `output_path` defined in `config.txt`.
### Input Requirements:
- Short-term closure phases (from `PhaseBias_02_Loop_Closures.py`).
- Configuration parameters, including thresholds and temporal settings, defined in `config.txt`.
### Output Files:
- `X_base_ifgs_biases.npy`: Stores the estimated bias terms for the base interferograms.
"""
if "--help" in sys.argv:
print(HELP_TEXT)
sys.exit(0)
###############################################################################
# Config file path
config_file = "config.txt"
# Check if config file exists
if not os.path.exists(config_file):
raise FileNotFoundError(
f"Error: The configuration file '{config_file}' was not found in the script's directory."
)
# Initialize the configparser
config = configparser.ConfigParser()
# Read the config.txt file
config.read(config_file)
# Define required parameters
required_parameters = [
"root_path",
"frame",
"start",
"end",
"interval",
"nlook",
"LiCSAR_data",
"a1_6_day",
"a2_6_day",
"a1_12_day",
"a2_12_day",
"estimate_an_values",
]
# Initialize a dictionary to store parameters
parameters = {}
# Attempt to retrieve each parameter and catch errors
try:
parameters["root_path"] = config.get("DEFAULT", "root_path")
parameters["output_path"] = config.get("DEFAULT", "output_path")
parameters["frame"] = config.get("DEFAULT", "frame")
parameters["start"] = config.get("DEFAULT", "start")
parameters["end"] = config.get("DEFAULT", "end")
parameters["interval"] = config.getint("DEFAULT", "interval")
parameters["nlook"] = config.getint(
"DEFAULT", "nlook"
) # Assuming 'nlook' should be an integer
parameters["LiCSAR_data"] = config.get("DEFAULT", "LiCSAR_data")
parameters["a1_6_day"] = config.getfloat("DEFAULT", "a1_6_day")
parameters["a2_6_day"] = config.getfloat("DEFAULT", "a2_6_day")
parameters["a1_12_day"] = config.getfloat("DEFAULT", "a1_12_day")
parameters["a2_12_day"] = config.getfloat("DEFAULT", "a2_12_day")
parameters["estimate_an_values"] = config.get("DEFAULT", "estimate_an_values")
except configparser.NoOptionError as e:
# Error message if a required parameter is missing
missing_param = str(e).split(": ")[1]
raise ValueError(
f"Error: Required parameter '{missing_param}' is missing in '{config_file}'. Please check the file contents."
)
except configparser.Error as e:
# General error for any configparser-related issues
raise ValueError(f"Error while reading '{config_file}': {e}")
# Assign to individual variables for easy access
root_path = parameters["root_path"]
output_path = parameters["output_path"]
frame = parameters["frame"]
start = parameters["start"]
end = parameters["end"]
interval = parameters["interval"]
nlook = parameters["nlook"]
LiCSAR_data = parameters["LiCSAR_data"]
estimate_an_values = parameters["estimate_an_values"]
# Initialize a1 and a2 with None for safety
a1 = None
a2 = None
print("estimate_an_values is ", estimate_an_values)
# Check if estimate_an_values is 'yes'
if estimate_an_values == "yes":
an_file_path = os.path.join(output_path, "Data", "an.txt")
# Try reading the file
try:
if os.path.exists(an_file_path):
print(f"Reading 'a' values from {an_file_path}...")
# Read the file and load the values
with open(an_file_path, "r") as file:
for line in file:
line = line.strip()
if line.startswith("a1="):
a1 = float(line.split("=")[1])
elif line.startswith("a2="):
a2 = float(line.split("=")[1])
# Check if both a1 and a2 were found
if a1 is None or a2 is None:
print(
"Warning: Missing a1 or a2 in an.txt. Switching to default values from config file."
)
raise ValueError("Incomplete a1 or a2 values.")
else:
print(
f"Warning: {an_file_path} does not exist. Switching to default values from config file."
)
raise FileNotFoundError
except (FileNotFoundError, ValueError):
# Fallback to default values from config file
if interval == 6:
a1 = parameters["a1_6_day"]
a2 = parameters["a2_6_day"]
else:
a1 = parameters["a1_12_day"]
a2 = parameters["a2_12_day"]
else:
# Use default values from the config file
print("Using default 'an' values from the config file.")
if interval == 6:
a1 = parameters["a1_6_day"]
a2 = parameters["a2_6_day"]
else:
a1 = parameters["a1_12_day"]
a2 = parameters["a2_12_day"]
# Print the chosen values
print(f"Final values - a1: {a1}, a2: {a2}")
##################################################### Loop Closure calculation #####################################################
####################################################################################################################################
####################################################################################################################################
track = frame[0:3]
if track[0] == "0":
track = track[1:3]
if track[0] == "0":
track = track[1:2]
with_temporals = "yes"
apply_to_all = "no" # in case of with_temporal='yes', we can decide if you want to use the temporal to all ifgs (i.e. apply_to_all='yes'), or just to those that can not be corrected (i.e. apply_to_all='no')
w = 0.1 # the weigth of the temporal smoothing constraints
#######
coh_thresh = 11 # threhsold on the coherence values. In this version it is off
min_num_eq = 10 # I used 10 in all my experiments. min number of equations in the least square inversion.
############################### Reading input data #############################################
##################### Read ifgs:
#print("Reading all ifgs...")
## Define the path components
#sub_dir = "Data"
#filename_pattern = "All_ifgs_*" # Pattern to match files starting with "All_ifgs"
#
## Construct the full file path with the refined pattern
#file_path_pattern = os.path.join(output_path, sub_dir, filename_pattern)
## Use glob to find the file and ensure it exists
#file_list = glob.glob(file_path_pattern)
#if file_list:
# file_path = file_list[0] # Get the single file path directly
#
# # Load the data from the file
# with open(file_path, "rb") as file:
# all_ifgs = pickle.load(file)
#else:
# raise FileNotFoundError(
# f"No file matching '{filename_pattern}' was found in '{os.path.join(output_dir, sub_dir)}'."
# )
#print("Reading ifgs completed.")
####################### Read coh:
#print("\nReading all coherence data...")
## Define the path components
#sub_dir = "Data"
#filename_pattern = "All_coh_*" # Pattern to match files starting with "All_ifgs"
#
## Construct the full file path with the refined pattern
#file_path_pattern = os.path.join(output_path, sub_dir, filename_pattern)
## Use glob to find the file and ensure it exists
#file_list = glob.glob(file_path_pattern)
#if file_list:
# file_path = file_list[0] # Get the single file path directly
#
# # Load the data from the file
# with open(file_path, "rb") as file:
# all_coh = pickle.load(file)
#else:
# raise FileNotFoundError(
# f"No file matching '{filename_pattern}' was found in '{os.path.join(output_dir, sub_dir)}'."
# )
#print("Reading coherence data completed.")
##################### Read Loops
print("\nReading all loop closures...")
sub_dir = "Data"
filename_pattern = "All_loops_*" # Pattern to match files starting with "All_ifgs"
# Construct the full file path with the refined pattern
file_path_pattern = os.path.join(output_path, sub_dir, filename_pattern)
# Use glob to find the file and ensure it exists
file_list = glob.glob(file_path_pattern)
if file_list:
file_path = file_list[0] # Get the single file path directly
# Load the data from the file
with open(file_path, "rb") as file:
all_loops = pickle.load(file)
else:
raise FileNotFoundError(
f"No file matching '{filename_pattern}' was found in '{os.path.join(output_dir, sub_dir)}'."
)
print("Reading loop closures completed.")
all_cat = []
for cat in all_loops:
all_cat.append(cat)
### stacking all the ifgs 6/12/18 in a numpy var all_ifgs
print(
"Extracting the required interferograms(up to 3 epochs), and the corresponding loop closures for inversion..."
)
#desired_categories = [interval, 2 * interval, 3 * interval]
#all_ifgs, _, existing_ifgs_index = read_orig_ifgs_coh(
# all_ifgs, all_coh, desired_categories
#)
######### forming 12-6 and 18-6 loop closures from the imported data
#################################################################
loop_12 = np.array(all_loops[2 * interval][interval], dtype=object)
#coh_12 = np.array(all_coh[2 * interval][:], dtype=object)
loop_18 = np.array(all_loops[3 * interval][interval], dtype=object)
#coh_18 = np.array(all_coh[3 * interval][:], dtype=object)
############## finding dynamic pixel-based thresholds to remove the noisy loops
loop_12_orig = []
loop_18_orig = []
none_indices12 = []
none_indices18 = []
# refine loop_12 to exclude the none indices and create loop_12_orig
for i, arr in enumerate(loop_12):
if arr is not None:
(frame_row, frame_col) = np.shape(arr)
loop_12_orig.append(arr)
else:
none_indices12.append(i)
# refine loop_18 to exclude the none indices and create loop_18_orig
for i, arr in enumerate(loop_18):
if arr is not None:
loop_18_orig.append(arr)
else:
none_indices18.append(i)
loop_12_orig = np.array(loop_12_orig)
loop_18_orig = np.array(loop_18_orig)
### removing noisy loops
print(
"Masking noisy loop closures using circular moving average and standard deviaiton of the loop closures in time:"
)
# using circular_mean to calculate the mean phase value using complex numbers, and von_mises_variance to calculate the second moment of the Von Mises distribution
_, thresh_loop12 = circular_mean_and_variance_over_epochs(loop_12_orig, axis=0)
_, thresh_loop18 = circular_mean_and_variance_over_epochs(loop_18_orig, axis=0)
# Add a new axis at the beginning (axis=0) of these arrays to have shape (1, ...)
# These are the threshold vlaues obtained for each pixel that will be used for masking later
thresh_loop12 = np.expand_dims(thresh_loop12, axis=0)
thresh_loop18 = np.expand_dims(thresh_loop18, axis=0)
# calculate a temporal moving average for wrapped data
def moving_average(arr, window_size):
# Initialize an empty array to store the temporal averages
moving_averages = np.zeros_like(arr)
half_window = window_size // 2
### miroring data at both ends for window_size/2 at each end
mirrored_shape = (arr.shape[0] + window_size, arr.shape[1], arr.shape[2])
# Create an empty array to hold the mirrored data
mirrored_arr = np.empty(mirrored_shape, dtype=arr.dtype)
# Fill the mirrored array with the original data
mirrored_arr[window_size // 2 : -window_size // 2] = arr
# Mirror the data at the beginning
for i in range(window_size // 2):
# mirrored_arr[i] = arr[window_size // 2 - i]
mirrored_arr[i] = arr[min(half_window - i, arr.shape[0] - 1)]
# Mirror the data at the end
for i in range(window_size // 2):
# mirrored_arr[-(i + 1)] = arr[-(i + 1) - window_size // 2]
mirrored_arr[-(i + 1)] = arr[max(-1 - (half_window - i), 0)]
####
# Calculate temporal averages within each window
for t in range(half_window, mirrored_arr.shape[0] - half_window):
moving_averages[t - half_window, :, :] = np.angle(
np.nanmean(
np.exp(1j * (mirrored_arr[t - half_window : t + half_window, :, :])),
axis=0,
)
)
return moving_averages
# for loop 12
# Calculate distance between each epoch and the moving average for each pixel
print(
f"Calculating the moving average for {2 * interval} loop closures, followed by masking noisy loop closures..."
)
print(
"This may take a while, as it depends on the number of loops and the size of your dataset.\n"
)
window_size = 30
moving_avg = moving_average(loop_12_orig, window_size)
distances = np.abs(np.angle(np.exp(1j * (loop_12_orig - moving_avg))))
mask = distances > 4 * thresh_loop12 # it is 4*sigma
# Replace values with NaN where mask is True
loop_12_bk = loop_12_orig
loop_12_orig = np.where(mask, np.nan, loop_12_orig)
loop_12 = loop_12_orig.tolist()
for idx in none_indices12:
loop_12.insert(idx, None)
loop_12 = np.array(loop_12, dtype=object)
# for loop 18
# Calculate distance between each epoch and the moving average for each pixel
print(
f"Calculating the moving average for {3 * interval} loop closures, followed by masking noisy loop closures..."
)
print(
"This may take a while, as it depends on the number of loops and the size of your dataset.\n"
)
moving_avg = moving_average(loop_18_orig, window_size)
distances = np.abs(np.angle(np.exp(1j * (loop_18_orig - moving_avg))))
mask = distances > 4 * thresh_loop18 # it is 4*sigma
# Replace values with NaN where mask is True
loop_18_bk = loop_18_orig
loop_18_orig = np.where(mask, np.nan, loop_18_orig)
loop_18 = loop_18_orig.tolist()
for idx in none_indices18:
loop_18.insert(idx, None)
loop_18 = np.array(loop_18, dtype=object)
print("Masking of noisy loop closures is completed.")
# ################ Apply coherece thresholding
# print('shape loop_12 = ', np.shape(loop_12))
# print('shape loop_12_orig = ', np.shape(loop_12_orig))
# print('shape coh_12 = ', np.shape(coh_12))
# for i, arr in enumerate(loop_12):
# if arr is not None:
# (frame_row, frame_col) = np.shape(arr)
# loop_12[i] = np.where((coh_12[i] > coh_thresh), arr, np.nan)
#
#
# for i, arr in enumerate(loop_18):
# if arr is not None:
# loop_18[i] = np.where((coh_18[i] > coh_thresh), arr, np.nan)
#
#
#
len12 = len(loop_12) # number of 12 day loops including None
len18 = len(loop_18) # number of 18 day loops including None
######################## Forming the design matrix A ##############################
####################################################################################
print("Preparing the design matrix and observation vector for the inversion step...")
b = []
A = []
n_unk = (
len12 + 1
) # this in an initial value(i.e. the num of 6 biases). will be changed by the actual number of unk after considering the None values/missing
# print('n_unk = ', n_unk)
row = np.zeros(
n_unk, dtype=np.float32
) # each row of the design matrix A for the 12-day
for i in range(len12):
b.append(loop_12[i])
# print('np.shape(loop_12[i] = ', np.shape(loop_12[i]))
row[i : i + 2] = a1 - 1
A.append(row)
row = np.zeros(n_unk, dtype=np.float32)
row = np.zeros(
n_unk, dtype=np.float32
) # each row of the design matrix A for the 18-day
for i in range(len18):
b.append(loop_18[i])
row[i : i + 3] = a2 - 1
A.append(row)
row = np.zeros(n_unk, dtype=np.float32)
A = np.array(A)
b = np.array(b, dtype=object)
####################### removing the rows from b and A where b is None
mask = []
mask = np.array([arr is not None for arr in b])
# Convert the boolean mask to an integer mask
mask = np.nonzero(mask)
A = A[mask] # Filter rows of A based on the mask
b = b[mask]
b = b.tolist()
############ removing the columns of A where are values are zero (these are the unkonws which doesn't fall in any equations nor 12 neither 18 and thus cannot be corrected)
# Find the column indices where all values are zero
zero_columns = np.all(A == 0, axis=0)
## Get the indices of the zero columns
zero_column_indices = np.where(zero_columns)[0]
# Get the indices of the non-zero columns
non_zero_column_indices = np.where(~zero_columns)[
0
] # the indices of the unknowns that can be corrected
# Save the file
directory_path = os.path.join(output_path, "Data")
file_path = os.path.join(directory_path, f"indices_unknown_tobe_corrected.npy")
np.save(file_path, non_zero_column_indices)
### Adding all the existing 6-day ifgs indices to non_zero_column_indices. We want to use estimate their biases in the second step.
A_bk = A # to keep a copy of A in case we want to esimate all 6-day biases with smoothing constraints
b_bk = b
all_column_indices = np.array(
range(A_bk.shape[1])
) # generating all indices in case we want to esimate all 6-day biases with smoothing constraints
A = A[:, non_zero_column_indices]
# finding the last column with value -1. this gives the number of 6-day biases that can be corrected
last_column_with_minus_1 = None
# Iterate through the columns from right to left
for col in range(len(A[0]) - 1, -1, -1):
if -1 in [row[col] for row in A]:
last_column_with_minus_1 = col
break
num_rows_before_temporals = A.shape[0]
################################# Least Square inversion ###############################
########################################################################################
# First Inversion: Without Temporal Smoothing Constraints
print("Starting the first inversion (without temporal smoothing constraints).")
print(
"This step estimates the bias terms that can be corrected based on observed loop closures."
)
damp_factor = 0
if apply_to_all == "no": # this is without using any temporal constraints
X1 = np.zeros((np.shape(A_bk)[1], frame_row, frame_col), dtype=np.float32)
# X1[:,:,:] = np.nan # after checking noticed this doesn't have any effect on the final vel
b_bk = np.array(b_bk)
total_pixels = frame_row * frame_col # Total number of pixels for progress bar
processed_pixels = 0 # Counter for processed pixels
print("Progress: [", end="", flush=True)
for row in range(frame_row):
for col in range(frame_col):
processed_pixels += 1
# Update progress bar
percentage = (processed_pixels / total_pixels) * 100
if processed_pixels % (total_pixels // 100) == 0: # Update every 1%
print(f"{int(percentage)}%", end="", flush=True)
sys.stdout.write(
"\rProgress: ["
+ "=" * (int(percentage) // 2)
+ " " * (50 - int(percentage) // 2)
+ "]"
)
non_nan_mask = ~np.isnan(b_bk[:, row, col])
bb = b_bk[non_nan_mask, row, col] # Remove NaN values
AA = A_bk[non_nan_mask, :] # Remove corresponding rows
if len(bb) > min_num_eq: # what is the min number of equation?
x, istop, itn, normr, normr2 = lsqr(
csc_array(AA), bb, damp=damp_factor
)[
:5
] # Using sparse matrix representation scipy.sparse.linalg
X1[:, row, col] = x
print("\nFirst inversion (without temporal smoothing constraints) completed.")
###########################
# Second Inversion: With Temporal Smoothing Constraints
print("Starting the second inversion (with temporal smoothing constraints).")
print(
"This step estimates all bias terms, including those that cannot be corrected, using temporal smoothing constraints."
)
if with_temporals == "yes": # This is using the temporal constranints on all unknowns
X2 = np.zeros((np.shape(A_bk)[1], frame_row, frame_col), dtype=np.float32)
# X2[:,:,:] = np.nan # after checking noticed this doesn't have any effect on the final vel
b_bk = np.array(b_bk)
#### Adding temporal constraints
row = np.zeros(
A_bk.shape[1], dtype=np.float32
) # additional rows the design matrix A for temporal constraints, setting that to zero again
for i in range(len(all_column_indices) - 2): # for all unknowns
row[i] = -1 * w
row[i + 1] = 2 * w
row[i + 2] = -1 * w
A_bk = np.vstack((A_bk, row))
row = np.zeros(
A_bk.shape[1], dtype=np.float32
) # additional rows the design matrix A for temporal constraints, setting that to zero again
num_temporals = len(A_bk) - len(b_bk)
# print('num_temporals is ', num_temporals)
######### Appending zeroes to b according to the added number of temporal constraints obtained by np.shape(A)[0] - np.shape(b)[0]
b_0 = np.zeros(
(np.shape(A_bk)[0] - np.shape(b)[0], frame_row, frame_col), dtype=np.float32
)
b_bk = np.vstack((b_bk, b_0))
thresh_n_eq = num_temporals # in case of using temporals, we don't want the nan pixels with zero equations with only using temporals
processed_pixels = 0 # Reset counter for second inversion
print("Progress: [", end="", flush=True)
for row in range(frame_row):
for col in range(frame_col):
processed_pixels += 1
# Update progress bar
percentage = (processed_pixels / total_pixels) * 100
if processed_pixels % (total_pixels // 100) == 0: # Update every 1%
print(f"{int(percentage)}%", end="", flush=True)
sys.stdout.write(
"\rProgress: ["
+ "=" * (int(percentage) // 2)
+ " " * (50 - int(percentage) // 2)
+ "]"
)
non_nan_mask = ~np.isnan(b_bk[:, row, col])
bb = b_bk[non_nan_mask, row, col] # Remove NaN values
AA = A_bk[non_nan_mask, :] # Remove corresponding rows
if len(bb) > thresh_n_eq:
x, istop, itn, normr, normr2 = lsqr(
csc_array(AA), bb, damp=damp_factor
)[
:5
] # Using sparse matrix representation scipy.sparse.linalg
X2[:, row, col] = x
print("\nSecond inversion (with temporal smoothing constraints) completed.")
####### combining X1 and X2 into X
X = np.zeros((np.shape(A_bk)[1], frame_row, frame_col), dtype=np.float32)
X[:, :, :] = np.nan
# Fill X with values from X1 according to non_zero_column_indices
for i, idx in enumerate(non_zero_column_indices):
X[idx, :, :] = X1[i, :, :]
# Fill in the missing values from X2
for i, idx in enumerate(all_column_indices):
if idx not in non_zero_column_indices:
X[idx, :, :] = X2[i, :, :]
# Ensure the dtype is appropriate for your data
X = X.astype(np.float32)
directory_path = os.path.join(output_path, "Data")
file_path = os.path.join(directory_path, f"X_base_ifgs_biases.npy")
np.save(file_path, X)
print("Inversion process completed. Results saved to:", file_path)
##########################################################################################################
@@ -0,0 +1,481 @@
#!/usr/bin/env python3
import numpy as np
from datetime import datetime
import pickle
import time
import os
from bin.generate_ifgs_from_epochs import generate_ifg_pairs
import configparser
import glob
from bin.resample import resample_geotiff
import sys
# sys.path.append(os.path.dirname(os.path.abspath(__file__)))
import bin
from bin.read_orig_ifgs_coh import read_orig_ifgs_coh
from bin.ifg_cc_totif import ifg_cc_2tif
import gc
###############################################################################
HELP_TEXT = """
PhaseBias_05_Correction.py
This script applies phase bias correction to desired interferograms using the estimated bias terms for the base interferograms. The corrected interferograms are saved in GeoTIFF format for further analysis.
### Workflow:
1. **Inputs:**
- **Original Wrapped Interferograms, and Coherence Data:** Obtained from step 1 (`PhaseBias_01_Read_Data.py`).
- **Estimated Bias Terms for Base Intierferograms:** Obtained from step 4 (`PhaseBias_04_Inversion.py`).
- **Calibration Parameters (*a_n*):** Estimated from step 3 (`PhaseBias_03_calibration_pars.py`).
- **max_con:** Defines the maximum number of connections to be corrected. For instance:
- `max_con=5` corrects interferograms up to 30-day intervals for a 6-day acquisition interval.
- Adjust `max_con` as needed.
2. **Bias Term Estimation for Desired Interferograms:**
- Bias terms for desired interferograms, δ_(i,i+n+1), are estimated using the relationship:
δ_(i,i+n+1) = a_n * (∑_(t=i)^(i+n) δ_(t,t+1) )
3. **Correction of Interferograms:**
- Using the estimated bias terms, the interferograms are corrected as follows:
φ_(i,i+n+1)^c = φ_(i,i+n+1) - δ_(i,i+n+1)
- Here, φ_(i,i+n+1) is the original interferogram, and φ_(i,i+n+1)^c is the corrected interferogram.
4. **Outputs:**
- Corrected interferograms are saved in GeoTIFF format in the `GEOC` directory under the `output_path` specified in `config.txt`.
### Output File Format:
- **Corrected Interferograms:** Saved in GeoTIFF format, organized by temporal baseline.
### Input Requirements:
- Original wrapped interferograms from step 1.
- Bias terms for base interferograms from step 4.
- Configuration parameters (e.g., `output_path`, `interval`) defined in `config.txt`.
### Output Directory:
- `GEOC` directory under `output_path`: Contains the corrected interferograms in GeoTIFF format, organized by temporal baseline.
"""
if "--help" in sys.argv:
print(HELP_TEXT)
sys.exit(0)
################################################################################
# Config file path
config_file = "config.txt"
# Check if config file exists
if not os.path.exists(config_file):
raise FileNotFoundError(
f"Error: The configuration file '{config_file}' was not found in the script's directory."
)
# Initialize the configparser
config = configparser.ConfigParser()
# Read the config.txt file
config.read(config_file)
# Define required parameters
required_parameters = [
"root_path",
"frame",
"start",
"end",
"interval",
"nlook",
"LiCSAR_data",
"a1_6_day",
"a2_6_day",
"a3_6_day",
"a4_6_day",
"a1_12_day",
"a2_12_day",
"a3_12_day",
"a4_12_day",
"estimate_an_values",
]
# Initialize a dictionary to store parameters
parameters = {}
# Attempt to retrieve each parameter and catch errors
try:
parameters["root_path"] = config.get("DEFAULT", "root_path")
parameters["output_path"] = config.get("DEFAULT", "output_path")
parameters["frame"] = config.get("DEFAULT", "frame")
parameters["start"] = config.get("DEFAULT", "start")
parameters["end"] = config.get("DEFAULT", "end")
parameters["interval"] = config.getint("DEFAULT", "interval")
parameters["nlook"] = config.getint(
"DEFAULT", "nlook"
) # Assuming 'nlook' should be an integer
parameters["LiCSAR_data"] = config.get("DEFAULT", "LiCSAR_data")
parameters["a1_6_day"] = config.getfloat("DEFAULT", "a1_6_day")
parameters["a2_6_day"] = config.getfloat("DEFAULT", "a2_6_day")
parameters["a3_6_day"] = config.getfloat("DEFAULT", "a3_6_day")
parameters["a4_6_day"] = config.getfloat("DEFAULT", "a4_6_day")
parameters["a1_12_day"] = config.getfloat("DEFAULT", "a1_12_day")
parameters["a2_12_day"] = config.getfloat("DEFAULT", "a2_12_day")
parameters["a3_12_day"] = config.getfloat("DEFAULT", "a3_12_day")
parameters["estimate_an_values"] = config.get("DEFAULT", "estimate_an_values")
except configparser.NoOptionError as e:
# Error message if a required parameter is missing
missing_param = str(e).split(": ")[1]
raise ValueError(
f"Error: Required parameter '{missing_param}' is missing in '{config_file}'. Please check the file contents."
)
except configparser.Error as e:
# General error for any configparser-related issues
raise ValueError(f"Error while reading '{config_file}': {e}")
# Assign to individual variables for easy access
root_path = parameters["root_path"]
output_path = parameters["output_path"]
frame = parameters["frame"]
start = parameters["start"]
end = parameters["end"]
interval = parameters["interval"]
nlook = parameters["nlook"]
LiCSAR_data = parameters["LiCSAR_data"]
estimate_an_values = parameters["estimate_an_values"]
start_date = datetime.strptime(start, "%Y%m%d")
end_date = datetime.strptime(end, "%Y%m%d")
uncor_only = 0 # in case of 1 only uses 6-12-18 uncorrected ifgs. it is based on the desired_lengths ifgs
max_con = 5 # in case of 5, it will correct up to 6*5=30-day ifgs.
#####################################################
# Root directory where the category directories are located
if LiCSAR_data == "yes":
track = frame[0:3] # extracting track number from frame id
if track[0] == "0":
track = track[1:3]
if track[0] == "0":
track = track[1:2]
root_directory = (
f"/gws/nopw/j04/nceo_geohazards_vol1/public/LiCSAR_products/{track}/{frame}"
)
else:
root_directory = root_path
############################################
# Initialize the an values with None for safety
an_values = [None] * (
max_con - 1
) # For max_con=5, this will create [None, None, None, None]
print("estimate_an_values is ", estimate_an_values)
# Check if estimate_an_values is 'yes'
if estimate_an_values == "yes":
an_file_path = os.path.join(output_path, "Data", "an.txt")
# Try reading the file
try:
if os.path.exists(an_file_path):
print(f"Reading 'a' values from {an_file_path}...")
# Read the file and load the an values dynamically
with open(an_file_path, "r") as file:
for line in file:
line = line.strip()
for i in range(
1, max_con
): # Loop through a1, a2, ..., a(max_con-1)
param_name = f"a{i}"
if line.startswith(f"{param_name}="):
an_values[i - 1] = float(line.split("=")[1])
# Check if all required an values were found
if any(value is None for value in an_values):
print(
"Warning: Missing one or more an values in an.txt. Switching to default values from config file."
)
raise ValueError("Incomplete an values.")
else:
print(
f"Warning: {an_file_path} does not exist. Switching to default values from config file."
)
raise FileNotFoundError
except (FileNotFoundError, ValueError):
# Fallback to default values from config file
print("Loading default 'an' values from config file...")
for i in range(1, max_con):
if interval == 6:
an_values[i - 1] = parameters[f"a{i}_6_day"]
else:
an_values[i - 1] = parameters[f"a{i}_12_day"]
else:
# Use default values from the config file
print("Using default 'an' values from the config file.")
for i in range(1, max_con):
if interval == 6:
an_values[i - 1] = parameters[f"a{i}_6_day"]
else:
an_values[i - 1] = parameters[f"a{i}_12_day"]
# Print the chosen an values
for i, value in enumerate(an_values, start=1):
print(f"Final value - a{i}: {value}")
############## generating ifg pairs between two epochs
# desired_lengths = [interval, 2*interval, 3*interval, 4*interval, 5*interval]
desired_lengths = [interval * i for i in range(1, max_con + 1)] # replacing the above
all_ifgs_string = generate_ifg_pairs(start_date, end_date, interval, desired_lengths)
##### reading original ifgs/coh #############################
####################################################################################
############################### Reading input data #############################################
#################### Read ifgs:
print("Reading all ifgs...")
# Define the path components
sub_dir = "Data"
filename_pattern = "All_ifgs_*" # Pattern to match files starting with "All_ifgs"
# Construct the full file path with the refined pattern
file_path_pattern = os.path.join(output_path, sub_dir, filename_pattern)
# Use glob to find the file and ensure it exists
file_list = glob.glob(file_path_pattern)
if file_list:
file_path = file_list[0] # Get the single file path directly
# Load the data from the file
with open(file_path, "rb") as file:
ifgs = pickle.load(file)
else:
raise FileNotFoundError(
f"No file matching '{filename_pattern}' was found in '{os.path.join(output_dir, sub_dir)}'."
)
###################### Read coh:
print("\nReading all coherence data...")
# Define the path components
sub_dir = "Data"
filename_pattern = "All_coh_*" # Pattern to match files starting with "All_ifgs"
# Construct the full file path with the refined pattern
file_path_pattern = os.path.join(output_path, sub_dir, filename_pattern)
# Use glob to find the file and ensure it exists
file_list = glob.glob(file_path_pattern)
if file_list:
file_path = file_list[0] # Get the single file path directly
# Load the data from the file
with open(file_path, "rb") as file:
coh = pickle.load(file)
else:
raise FileNotFoundError(
f"No file matching '{filename_pattern}' was found in '{os.path.join(output_dir, sub_dir)}'."
)
print("\nReading data completed.")
######## stacking all the ifgs 6/12/18 in a numpy var all_ifgs
desired_categories = desired_lengths
all_ifgs, all_coh, existing_ifgs_index = read_orig_ifgs_coh(
ifgs, coh, desired_categories
)
del ifgs, coh
gc.collect()
##### Reading the estimated bias terms as well as the indices of unknowns that can be corrected obtained in step 03 ##############
##############################################################################################
print("Correcting the interferograms...")
# Define the path components
sub_dir = "Data"
filename_pattern_X = "X_base*" # Pattern to match files starting with "X_base"
filename_pattern_indices = "indices*"
# Construct the full file path with the refined pattern
file_path_pattern_X = os.path.join(output_path, sub_dir, filename_pattern_X)
file_path_pattern_indices = os.path.join(output_path, sub_dir, filename_pattern_indices)
# Use glob to find the file and ensure it exists
file_list = glob.glob(file_path_pattern_X)
if file_list:
file_path = file_list[0] # Get the single file path directly
# Load the data from the file
with open(file_path, "rb") as file:
X = np.load(file)
else:
raise FileNotFoundError(
f"No file matching '{filename_pattern}' was found in '{os.path.join(output_dir, sub_dir)}'."
)
# print('Reading ifgs completed.')
# Use glob to find the file and ensure it exists
file_list = glob.glob(file_path_pattern_indices)
if file_list:
file_path = file_list[0] # Get the single file path directly
# Load the data from the file
with open(file_path, "rb") as file:
indices_unknown_tobe_corrected = np.load(file)
else:
raise FileNotFoundError(
f"No file matching '{filename_pattern}' was found in '{os.path.join(output_dir, sub_dir)}'."
)
#### loading indices of unknown that can be corrected and the estimated unknowns
indices_unknown_tobe_corrected_orig = indices_unknown_tobe_corrected.copy()
len_6_biases = indices_unknown_tobe_corrected[-1] + 1 # number of 6-day biases
all_column_indices = np.array(
range(len_6_biases)
) # generating all indices in case we want to esimate all 6-day biases with smoothing constraints.
indices_unknown_tobe_corrected = all_column_indices # in this case we had provided the corrections for all 6-day biases
# extending the indices_unknown_tobe_corrected in the original approach to have the indices of 12/18 correctable ifgs:
extended_indices = (
indices_unknown_tobe_corrected.copy()
) # because in this case indices_unknown_tobe_corrected referes to all_column_indices
X_extended = (
X.copy()
) # because in this case we have estimated all 6-day biases but we don't need them for the correction. we just need them to correct the existing 12/18 days based on the 6 days
extended_indices = extended_indices.tolist()
X_extended = X_extended.tolist()
# Generalized loop to handle any max_con
for n in range(2, max_con + 1): # Start from 2*interval and go up to (max_con)*interval
current_length = n * interval # Calculate the length (e.g., 12, 18, 24, ...)
if current_length in desired_lengths: # Check if this length is required
for i in range(len(indices_unknown_tobe_corrected) - (n - 1)):
last_item = extended_indices[-1] # Get the last index
extended_indices.append(last_item + 1) # Append the new index
# Sum up X values for the current length (n)
X_sum = sum(
X[i + j, :, :] for j in range(n)
) # Sum over n consecutive indices
# Append the result to X_extended using the corresponding an_values
X_extended.append(
an_values[n - 2] # an_values is 0-based, so use n-2
* np.angle(np.exp(complex(0 + 1j) * X_sum))
)
X = np.array(X_extended)
indices_unknown_tobe_corrected = extended_indices
del X_extended
#### correcting the ifgs (6/12/18) ########################
#################################################################
all_ifgs_cor = np.full_like(all_ifgs, None)
all_ifgs_cor[:, :, :] = np.nan
if uncor_only == 0: # if we want to use the corrected ifgs (using wrapped phases)
all_ifgs_cor[indices_unknown_tobe_corrected, :, :] = np.angle(
np.exp(
complex(0 + 1j)
* (all_ifgs[indices_unknown_tobe_corrected, :, :] - X[:, :, :])
)
)
else: # no need for correction
all_ifgs_cor[indices_unknown_tobe_corrected, :, :] = all_ifgs[
indices_unknown_tobe_corrected, :, :
]
### Outputting to disk ################
#############################################################################
# Create the directory (and parent directories) if they don't exist
GEOC_dir = "GEOC"
metadata_dir = "metadata"
output_wrap_dir = os.path.join(output_path, GEOC_dir)
os.makedirs(
output_wrap_dir, exist_ok=True
) # create the GEOC directory if it doesn't exist
template_tif_path = os.path.join(root_directory, metadata_dir, frame + ".geo.hgt.tif")
if nlook != 1:
resampled_tif_path = os.path.join(output_wrap_dir, frame + ".geo.hgt.tif")
resample_geotiff(template_tif_path, resampled_tif_path, nlook)
template_tif_path = resampled_tif_path
total_files = len(all_ifgs) # Total number of interferograms
processed_files = 0 # Counter for processed files
print(f"Writing the corrected interferograms to {output_wrap_dir}")
print("Progress: [", end="", flush=True)
time.sleep(3)
for i in range(len(all_ifgs)):
if i in indices_unknown_tobe_corrected:
# Writing progress bar
processed_files += 1
percentage = (processed_files / total_files) * 100
if processed_files % (total_files // 100) == 0: # Update progress every 1%
sys.stdout.write(
f"\rProgress: ["
+ "=" * (int(percentage) // 2)
+ " " * (50 - int(percentage) // 2)
+ f"] {int(percentage)}%"
)
sys.stdout.flush()
inpha = all_ifgs_cor[i, :, :] # your phase input, float32
incoh = all_coh[i, :, :] # your coh input. It can be either 0-255 or 0-1
output_phase_path = os.path.join(output_wrap_dir, all_ifgs_string[i])
output_cc_path = os.path.join(output_wrap_dir, all_ifgs_string[i])
# output_phase_path = output_wrap_dir + all_ifgs_string[i]
# output_cc_path = output_wrap_dir + all_ifgs_string[i]
os.makedirs(output_phase_path, exist_ok=True)
os.makedirs(output_cc_path, exist_ok=True)
output_phase_file = (
output_phase_path + "/" + all_ifgs_string[i] + ".geo.diff_pha.tif"
)
output_cc_file = output_cc_path + "/" + all_ifgs_string[i] + ".geo.cc.tif"
ifg_cc_2tif(inpha, output_phase_file, template_tif_path)
ifg_cc_2tif(incoh, output_cc_file, template_tif_path)
print("\nAll corrected interferograms have been written to disk.")
@@ -0,0 +1,43 @@
[DEFAULT]
# That path to interferograms directory. In case of LiCSAR data set LiCSAR_public='yes', and provide the frame id
root_path = /gws/nopw/j04/nceo_geohazards_vol1/public/LiCSAR_products.public/44/044A_04728_131314
output_path = /work/scratch-pw4/earyma/ESA_project/044A_04728_131314
LiCSAR_data=no
frame=044A_04728_131314
# Provide the start and end dates of the time-series that you want to calculate the phase bias correction
start=20170513
end=20210504
#Provide the data acquisition interval: 6-day or 12-day
interval=6
# If you want to apply further multilooking to interferograms (expand the explanation)
nlook=10
# The calibration parameters 'an' can be estimated from the data by specifying the number of parameters to be determined. For instance, setting num_a=2 indicates that
#a1 and a2 will be estimated.
num_a=2
### an parameters
# in case of yes the an values will be estimated from the data, otherwise the default values given below will be used
estimate_an_values=no
# Using 6-days interval
a1_6_day=0.50
a2_6_day=0.36
a3_6_day=0.299
a4_6_day=0.2476
# using 12-day interval
a1_12_day=0.494
a2_12_day=0.297
a3_12_day=0.24
a4_12_day=0.22
@@ -0,0 +1,45 @@
[DEFAULT]
# That path to interferograms directory. In case of LiCSAR data set LiCSAR_public='yes', and provide the frame id
root_path = /gws/nopw/j04/nceo_geohazards_vol1/public/LiCSAR_products.public/44/044A_04728_131314
output_path = /work/scratch-pw4/earyma/ESA_project/044A_04728_131314
LiCSAR_data=no
frame=044A_04728_131314
# Provide the start and end dates of the time-series that you want to calculate the phase bias correction
start=20170513
end=20210504
#Provide the data acquisition interval: 6-day or 12-day
# Modified for 12-day and 24-day data
interval=12
# If you want to apply further multilooking to interferograms (expand the explanation)
nlook=10
# The calibration parameters 'an' can be estimated from the data by specifying the number of parameters to be determined. For instance, setting num_a=2 indicates that
#a1 and a2 will be estimated.
num_a=2
### an parameters
# in case of yes the an values will be estimated from the data, otherwise the default values given below will be used
# Modified: estimate from data for 12-day intervals
estimate_an_values=yes
# Using 6-days interval (original)
a1_6_day=0.50
a2_6_day=0.36
a3_6_day=0.299
a4_6_day=0.2476
# using 12-day interval (for 12-day base interferograms)
# These values will be used if estimate_an_values=no
a1_12_day=0.494
a2_12_day=0.297
a3_12_day=0.24
a4_12_day=0.22
Binary file not shown.

After

Width:  |  Height:  |  Size: 372 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

@@ -0,0 +1,121 @@
#! /bin/csh -f
echo "*** S1_import_SLC_from_zipfiles: Script to read in and concatenate S1 TOPS SLC from zip files ***"
echo "*** Copyright 2023 Gamma Remote Sensing, v2.3 19-Apr-2023 uw/cm ***"
echo ""
if ($#argv < 1)then
echo "usage: S1_import_SLC_from_zipfiles <zipfile_list> [burst_number_table_ref] [pol] [dtype] [swath_flag] [OPOD_dir] [cleaning] [noise_mode]"
echo " zipfile_list (input) ASCII file containing S1 zip filename(s) of one data take (one per line, in correct sequence)"
echo " (other values are vv, vh, hh, hv)"
echo " dtype output data type (enter - for default)"
echo " 0: FCOMPLEX (default)"
echo " 1: SCOMPLEX"
echo " "
echo "resulting files: burst SLC files (per polarization, with SLC_tab, SLC, SLC_par, TOPS_par and optionally SLC.noise)"
echo "(concatenated, empty bursts added where necessary) at selected polarizations"
echo " "
exit
endif
# 6-Jan-2023: logfile name updated to be the same on every platform
set zipfile_list = $1
# in this case it generates temp.burst_number_table_ref
set dtype = "0" # 0: FCOMPLEX
if ($#argv >= 2) then
if ( "$2" != "-" ) then
set dtype = $2
endif
endif
set zipfile=`date "+%Y%m%d_%H%M%S"`
set logfile = "LT1_import_SLC_from_zipfiles.$zipfile.logfile"
echo "the processing is documented in the logfile: $logfile"
echo "COMMAND_used: $0 $1 $2 " > $logfile
date >> $logfile
echo "" >> $logfile
##############################################################################
if (-e "$1" == 0) then
echo "ERROR: zipfile_list ($1) does not exist"; exit(-1)
else
#determine number of rows of $zipfile_list
set zipfile=`awk '(NR>=1){print NF}' $zipfile_list`
set nrows=`echo "$zipfile" | awk '(NR==1){print NF}'`
endif
set i="1"
while ( "$i" <= "$nrows" )
# interpret names, check consistency of names
# read first zipfile name and reduce it to filename without path
set zipfile = `awk '(NR=='"$i"'){print $1}' $zipfile_list`
if ( -e $zipfile == "0" ) then
echo "ERROR: zipfile number $1 ($zipfile) does not exist"; exit(-1)
endif
set zipfile = `awk '(NR=='"$i"'){print $1}' $zipfile_list`
# set l = `echo "$zipfile" | awk '{print length($1)}'`
set m = `echo "$zipfile tar.gz" | awk '{print match($1,$2)-71}'`
set filename_without_path = `echo "$zipfile $m" | awk '{print substr($1,$2,70)}'`
set path_only = `echo "$zipfile $m" | awk '{print substr($1,1,$2-1)}'`
# echo "$path_only $filename_without_path"
echo "$filename_without_path"
echo "$path_only"
set sensor = `echo "$filename_without_path" | awk '{print substr($1,1,4)}'`
set mode = `echo "$filename_without_path" | awk '{print substr($1,15,6)}'`
set polar = `echo "$filename_without_path" | awk '{print substr($1,54,2)}'`
set level = `echo "$filename_without_path" | awk '{print substr($1,50,3)}'`
set date = `echo "$filename_without_path" | awk '{print substr($1,41,8)}'`
set orbit = `echo "$filename_without_path" | awk '{print substr($1,22,6)}'`
set product = `echo "$filename_without_path" | awk '{print substr($1,61,10)}'`
echo "sensor: $sensor mode: $mode polar: $polar level: $level date: $date orbit: $orbit product: $product"
if ( "$level" != "SLC" ) then
echo "ERROR: type indicated in zipfile ($type) is not SLC"; exit(-1)
endif
set GeoTIFF = `tar -tzf $zipfile | grep "tiff" | awk '{print $1}'`
set xml_name = `tar -tzf $zipfile | grep "meta.xml" | awk '{print $1}'`
set num = `grep "$date" $zipfile_list | wc -l `
if ( ! -d $date ) then
mkdir $date
endif
if ( ! -d tmp_data_dir ) then
mkdir tmp_data_dir
endif
if ( $num>1 ) then
set SLC = ${date}_$product.slc
set SLC_par = ${date}_$product.slc.par
set SLC1 = ${date}_$product.slc.update
set SLC1_par = ${date}_$product.slc.update.par
else
set SLC = $date.slc
set SLC_par = $date.slc.par
set SLC1 = $date.slc.update
set SLC1_par = $date.slc.update.par
endif
tar -xzv -C tmp_data_dir -f $zipfile $GeoTIFF
tar -xzv -C tmp_data_dir -f $zipfile $xml_name
echo "COMMAND: par_LT1_SLC ./tmp_data_dir/$GeoTIFF ./tmp_data_dir/$xml_name ./$date/$SLC_par ./$date/$SLC "
par_LT1_SLC ./tmp_data_dir/$GeoTIFF ./tmp_data_dir/$xml_name ./$date/$SLC_par ./$date/$SLC
echo "COMMAND: par_LT1_SLC ./tmp_data_dir/$GeoTIFF ./tmp_data_dir/$xml_name ./$date/$SLC1 ./$date/$SLC1_par "
par_LT1_SLC_YSLi ./tmp_data_dir/$GeoTIFF ./tmp_data_dir/$xml_name ./$date/$SLC1 ./$date/$SLC1_par 0
grep "state_vector" ./$date/$SLC1_par | awk -F ' ' '{printf " %s %.5f %.5f %.5f %s %s\n", $1, $2, $3, $4, $5,$6}' | awk '{if (NR%2==1){print $0,"m/s"}else{print $0,"m"}}' | awk 'NR<=3 {print $1,$2}' >tmp1
grep "state_vector" ./$date/$SLC1_par | awk -F ' ' '{printf " %s %.5f %.5f %.5f %s %s\n", $1, $2, $3, $4, $5,$6}' | awk '{if (NR%2==1){print $0,"m/s"}else{print $0,"m"}}' | awk 'NR>3 {print $0}' >tmp2
set histchars=""
awk '!/state_vector/ ' ./$date/$SLC_par >tmp
cat tmp tmp1 tmp2 > ./$date/$SLC_par
rm tmp1 tmp tmp2
set i = `echo "$i" | awk '{printf "%d", $1+1}'`
end
rm -rf *.logfile tmp_data_dir
@@ -0,0 +1,126 @@
#! /bin/csh -f
echo "*** S1_import_SLC_from_zipfiles: Script to read in and concatenate S1 TOPS SLC from zip files ***"
echo "*** Copyright 2023 Gamma Remote Sensing, v2.3 19-Apr-2023 uw/cm ***"
echo ""
if ($#argv < 1)then
echo "usage: S1_import_SLC_from_zipfiles <zipfile_list> [burst_number_table_ref] [pol] [dtype] [swath_flag] [OPOD_dir] [cleaning] [noise_mode]"
echo " zipfile_list (input) ASCII file containing S1 zip filename(s) of one data take (one per line, in correct sequence)"
echo " (other values are vv, vh, hh, hv)"
echo " dtype output data type (enter - for default)"
echo " 0: FCOMPLEX (default)"
echo " 1: SCOMPLEX"
echo " "
echo "resulting files: burst SLC files (per polarization, with SLC_tab, SLC, SLC_par, TOPS_par and optionally SLC.noise)"
echo "(concatenated, empty bursts added where necessary) at selected polarizations"
echo " "
exit
endif
# 6-Jan-2023: logfile name updated to be the same on every platform
set zipfile_list = $1
# in this case it generates temp.burst_number_table_ref
set dtype = "0" # 0: FCOMPLEX
if ($#argv >= 2) then
if ( "$2" != "-" ) then
set dtype = $2
endif
endif
set zipfile=`date "+%Y%m%d_%H%M%S"`
set logfile = "LT1_import_SLC_from_zipfiles.$zipfile.logfile"
echo "the processing is documented in the logfile: $logfile"
echo "COMMAND_used: $0 $1 $2 " > $logfile
date >> $logfile
echo "" >> $logfile
##############################################################################
if (-e "$1" == 0) then
echo "ERROR: zipfile_list ($1) does not exist"; exit(-1)
else
#determine number of rows of $zipfile_list
set zipfile=`awk '(NR>=1){print NF}' $zipfile_list`
set nrows=`echo "$zipfile" | awk '(NR==1){print NF}'`
endif
# interpret names, check consistency of names
# read first zipfile name and reduce it to filename without path
set zipfile = `awk '(NR=='"1"'){print $1}' $zipfile_list`
if ( -e $zipfile == "0" ) then
echo "ERROR: zipfile number $1 ($zipfile) does not exist"; exit(-1)
endif
set zipfile = `awk '(NR=='"1"'){print $1}' $zipfile_list`
set input_basename = `basename "$zipfile"`
set input_mode = "archive"
if ( `echo "$input_basename" | grep -c ".tar.gz$"` > 0 ) then
set filename_without_path = `echo "$input_basename" | sed 's/\.tar\.gz$//'`
set GeoTIFF = `tar -tzf $zipfile | grep "tiff" | awk '{print $1}'`
set xml_name = `tar -tzf $zipfile | grep "meta.xml" | awk '{print $1}'`
if ( ! -d tmp_data_dir ) then
mkdir tmp_data_dir
endif
tar -xzv -C tmp_data_dir -f $zipfile $GeoTIFF
tar -xzv -C tmp_data_dir -f $zipfile $xml_name
set input_tiff = ./tmp_data_dir/$GeoTIFF
set input_xml = ./tmp_data_dir/$xml_name
else if ( `echo "$input_basename" | grep -c ".tiff$"` > 0 ) then
set input_mode = "scene"
set filename_without_path = `echo "$input_basename" | sed 's/\.tiff$//'`
set input_tiff = $zipfile
set input_xml = `echo "$zipfile" | sed 's/\.tiff$/.meta.xml/'`
if ( -e "$input_xml" == 0 ) then
echo "ERROR: meta xml for scene input does not exist ($input_xml)"; exit(-1)
endif
else
echo "ERROR: unsupported LT-1 input ($zipfile), only .tar.gz or .tiff are supported"; exit(-1)
endif
# echo "$filename_without_path"
set sensor = `echo "$filename_without_path" | awk '{print substr($1,1,3)}'`
set mode = `echo "$filename_without_path" | awk '{print substr($1,15,5)}'`
set polar = `echo "$filename_without_path" | awk '{print substr($1,54,2)}'`
set level = `echo "$filename_without_path" | awk '{print substr($1,50,3)}'`
set date = `echo "$filename_without_path" | awk '{print substr($1,41,8)}'`
set orbit = `echo "$filename_without_path" | awk '{print substr($1,22,5)}'`
set product = `echo "$filename_without_path" | awk '{print substr($1,61,10)}'`
echo "sensor: $sensor mode: $mode polar: $polar level: $level date: $date orbit: $orbit product: $product"
if ( "$level" != "SLC" ) then
echo "ERROR: type indicated in zipfile ($type) is not SLC"; exit(-1)
endif
set num = `grep "$date" t_$date | wc -l `
if ( $num>1 ) then
set SLC = ${date}_${product}.slc
set SLC_par = ${date}_${product}.slc.par
set SLC1 = ${date}_${product}.slc.update
set SLC1_par = ${date}_${product}.slc.update.par
else
set SLC = $date.slc
set SLC_par = $date.slc.par
set SLC1 = $date.slc.update
set SLC1_par = $date.slc.update.par
endif
echo "COMMAND: par_LT1_SLC $input_tiff $input_xml ./$SLC_par ./$SLC "
par_LT1_SLC $input_tiff $input_xml ./$SLC_par ./$SLC
echo "COMMAND: par_LT1_SLC $input_tiff $input_xml ./$SLC1 ./$SLC1_par "
par_LT1_SLC_YSLi $input_tiff $input_xml ./$SLC1 ./$SLC1_par 0
grep "state_vector" ./$SLC1_par | awk -F ' ' '{printf " %s %.5f %.5f %.5f %s %s\n", $1, $2, $3, $4, $5,$6}' | awk '{if (NR%2==1){print $0,"m/s"}else{print $0,"m"}}' | awk 'NR<=3 {print $1,$2}' >tmp1
grep "state_vector" ./$SLC1_par | awk -F ' ' '{printf " %s %.5f %.5f %.5f %s %s\n", $1, $2, $3, $4, $5,$6}' | awk '{if (NR%2==1){print $0,"m/s"}else{print $0,"m"}}' | awk 'NR>3 {print $0}' >tmp2
set histchars=""
awk '!/state_vector/ ' ./$SLC_par >tmp
cat tmp tmp1 tmp2 > ./$SLC_par
rm tmp1 tmp tmp2
rm -rf *.logfile tmp_data_dir
@@ -0,0 +1,202 @@
#! /usr/bin/env python
#'''
##################################################################################
# #
# Author: Yun-Meng Cao #
# Email : ymcmrs@gmail.com #
# Date : February, 2017 #
# #
# Split beam of SLC: backward and forward SLC image generation #
# #
##################################################################################
#'''
import numpy as np
import os
import sys
import subprocess
import getopt
import time
import glob
from pyint import _utils as ut
import argparse
INTRODUCTION = '''
------------------------------------------------------------------------------------------
Split beam of original SLC to generate sub-aperture SLC: backward- and forward-SLCs.
'''
EXAMPLE = '''
Usage:
MAI_SLC_gamma.py projectName Mdate Sdate
MAI_SLC_gamma.py PacayaT163TsxHhA 20150102 20150601
------------------------------------------------------------------------------------------
'''
def check_variable_name(path):
s=path.split("/")[0]
if len(s)>0 and s[0]=="$":
p0=os.getenv(s[1:])
path=path.replace(path.split("/")[0],p0)
return path
def read_template(File, delimiter='='):
'''Reads the template file into a python dictionary structure.
Input : string, full path to the template file
Output: dictionary, pysar template content
Example:
tmpl = read_template(KyushuT424F610_640AlosA.template)
tmpl = read_template(R1_54014_ST5_L0_F898.000.pi, ':')
'''
template_dict = {}
for line in open(File):
line = line.strip()
c = [i.strip() for i in line.split(delimiter, 1)] #split on the 1st occurrence of delimiter
if len(c) < 2 or line.startswith('%') or line.startswith('#'):
next #ignore commented lines or those without variables
else:
atrName = c[0]
atrValue = str.replace(c[1],'\n','').split("#")[0].strip()
atrValue = check_variable_name(atrValue)
template_dict[atrName] = atrValue
return template_dict
def ras2jpg(input, strTitle):
call_str = "convert " + input + ".ras " + input + ".jpg"
os.system(call_str)
call_str = "convert " + input + ".jpg -resize 250 " + input + ".thumb.jpg"
os.system(call_str)
call_str = "convert " + input + ".jpg -resize 500 " + input + ".bthumb.jpg"
os.system(call_str)
call_str = "$INT_SCR/addtitle2jpg.pl " + input + ".thumb.jpg 14 " + strTitle
os.system(call_str)
call_str = "$INT_SCR/addtitle2jpg.pl " + input + ".bthumb.jpg 24 " + strTitle
os.system(call_str)
def UseGamma(inFile, task, keyword):
if task == "read":
f = open(inFile, "r")
while 1:
line = f.readline()
if not line: break
if line.count(keyword) == 1:
strtemp = line.split(":")
value = strtemp[1].strip()
return value
print("Keyword " + keyword + " doesn't exist in " + inFile)
f.close()
def cmdLineParse():
parser = argparse.ArgumentParser(description='Split beam of original SLC to generate sub-aperture SLC: backward- and forward-SLCs',\
formatter_class=argparse.RawTextHelpFormatter,\
epilog=INTRODUCTION+'\n'+EXAMPLE)
parser.add_argument('projectName',help='projectName for processing.')
parser.add_argument('Mdate',help='Master date.')
parser.add_argument('Sdate',help='Slave date.')
inps = parser.parse_args()
return inps
def main(argv):
start_time = time.time()
inps = cmdLineParse()
Mdate = inps.Mdate
Sdate = inps.Sdate
projectName = inps.projectName
scratchDir = os.getenv('SCRATCHDIR')
templateDir = os.getenv('TEMPLATEDIR')
templateFile = templateDir + "/" + projectName + ".template"
templateDict=ut.update_template(templateFile)
rlks = templateDict['range_looks']
azlks = templateDict['azimuth_looks']
masterDate = templateDict['masterDate']
coregCoarse = templateContents['Coreg_Coarse']
if 'Squint_MAI' in templateContents: Squint = templateContents['Squint_MAI']
else: Squint = '0.5'
projectDir = scratchDir + '/' + projectName
demDir = scratchDir + '/' + projectName + '/DEM'
slcDir = scratchDir + '/' + projectName + '/SLC'
rslcDir = scratchDir + '/' + projectName + '/RSLC'
ifgDir = projectDir + '/MAIifg'
if not os.path.isdir(ifgDir): os.mkdir(ifgDir)
Pair = Mdate + '-' + Sdate
workDir = ifgDir + '/' + Pair
if not os.path.isdir(workDir): os.mkdir(workDir)
# input slcs
#######################################################################
Mamp = rslcDir + '/' + Mdate + '/' + Mdate + '_' + rlks + 'rlks.amp'
MampPar = rslcDir + '/' + Mdate + '/' + Mdate + '_' + rlks + 'rlks.amp.par'
Samp = rslcDir + '/' + Sdate + '/' + Sdate + '_' + rlks + 'rlks.amp'
SampPar = rslcDir + '/' + Sdate + '/' + Sdate + '_' + rlks + 'rlks.amp.par'
Mrslc = rslcDir + '/' + Mdate + '/' + Mdate + '.rslc'
MrslcPar = rslcDir + '/' + Mdate + '/' + Mdate + '.rslc.par'
Srslc = rslcDir + '/' + Sdate + '/' + Sdate + '.rslc'
SrslcPar = rslcDir + '/' + Sdate + '/' + Sdate + '.rslc.par'
HGT = demDir + '/' + masterDate + '_' + rlks + 'rlks.rdc.dem'
MasterPar = rslcDir + '/' + masterDate + '/' + masterDate + '.rslc.par'
# split slcs
MFslcImg = workDir + "/" + Mdate + ".F.slc"
MFslcPar = workDir + "/" + Mdate + ".F.slc.par"
SFslcImg = workDir + "/" + Sdate + ".F.slc"
SFslcPar = workDir + "/" + Sdate + ".F.slc.par"
MBslcImg = workDir + "/" + Mdate + ".B.slc"
MBslcPar = workDir + "/" + Mdate + ".B.slc.par"
SBslcImg = workDir + "/" + Sdate + ".B.slc"
SBslcPar = workDir + "/" + Sdate + ".B.slc.par"
print(MFslcImg + " "+ MslcImg)
# Multi-aperture processing
call_str = '$GAMMA_BIN/sbi_filt '+ MslcImg + ' ' + MrslcPar + ' '+SrslcPar + ' ' + MFslcImg + ' '+ MFslcPar + ' ' + MBslcImg + ' ' + MBslcPar + ' ' + Squint
os.system(call_str)
print(call_str)
call_str = '$GAMMA_BIN/sbi_filt '+ SslcImg + ' ' + SrslcPar + ' '+MrslcPar + ' ' + SFslcImg + ' '+ SFslcPar + ' ' + SBslcImg + ' ' + SBslcPar + ' ' + Squint
os.system(call_str)
sys.exit(1)
if __name__ == '__main__':
main(sys.argv[:])
@@ -0,0 +1,134 @@
#! /usr/bin/env python
#'''
##################################################################################
# #
# Author: Wei Chen #
# Email : chenweicug@gmail.com #
# Date : May,25th 2021 #
# #
# Split beam of SLC: backward and forward SLC image generation #
# #
##################################################################################
#'''
import numpy as np
import os
import sys
import subprocess
import getopt
import time
import glob
import argparse
from pyint import _utils as ut
def get_s1_date(raw_file):
file0 = os.path.basename(raw_file)
date = file0[17:25]
return date
def get_satellite(raw_file):
if 'S1A_IW_SLC_' in raw_file:
s0 = 'A'
else:
s0 = 'B'
return s0
def cmdLineParse():
parser = argparse.ArgumentParser(description='Generate SLC from Sentinel-1 raw data with orbit correction using GAMMA.',\
formatter_class=argparse.RawTextHelpFormatter,\
epilog=INTRODUCTION+'\n'+EXAMPLE)
parser.add_argument('projectName', help='project name. e.g., ChangningT55S1A')
parser.add_argument('Mdate',help='date to be processed. e.g., 20180101')
parser.add_argument('Sdate',help='date to be processed. e.g., 20180113')
inps = parser.parse_args()
return inps
INTRODUCTION = '''
-------------------------------------------------------------------
Split beam of original SLC to generate sub-aperture SLC: backward- and forward-SLCs
'''
EXAMPLE = """Usage:
MAI_SLC_Gamma.py projectName Mdate Sdate
MAI_SLC_Gamma.py ChangningT55S1A 20180517 20180529
-------------------------------------------------------------------
"""
def main(argv):
inps = cmdLineParse()
projectName = inps.projectName
Mdate = inps.Mdate
Sdate = inps.Sdate
scratchDir = os.getenv('SCRATCHDIR')
projectDir = scratchDir + '/' + projectName
templateDir = os.getenv('TEMPLATEDIR')
templateFile = templateDir + "/" + projectName + ".template"
templateDict=ut.update_template(templateFile)
slcDir = projectDir + '/SLC'
down_dir = projectDir + '/DOWNLOAD'
workDir = projectDir + '/MAI'
rlks = templateDict['range_looks']
azlks = templateDict['azimuth_looks']
Mdate = templateDict['masterDate']
coregCoarse = templateDict['Coreg_Coarse']
if not os.path.isdir(workDir):
call_str="mkdir " + workDir
os.system(call_str)
if 'Squint_MAI' in templateDict: Squint = templateContents['Squint_MAI']
else: Squint = '0.5'
SslcDir = slcDir + "/" + Sdate
MslcDir = slcDir + "/" + Mdate
MslcImg = MslcDir + "/" + Mdate + ".slc"
MslcPar = MslcDir + "/" + Mdate + ".slc.par"
SslcImg = SslcDir + "/" + Sdate + ".slc"
SslcPar = SslcDir + "/" + Sdate + ".slc.par"
# split slcs
MFslcImg = workDir + "/" + Mdate + ".F.slc"
MFslcPar = workDir + "/" + Mdate + ".F.slc.par"
SFslcImg = workDir + "/" + Sdate + ".F.slc"
SFslcPar = workDir + "/" + Sdate + ".F.slc.par"
MBslcImg = workDir + "/" + Mdate + ".B.slc"
MBslcPar = workDir + "/" + Mdate + ".B.slc.par"
SBslcImg = workDir + "/" + Sdate + ".B.slc"
SBslcPar = workDir + "/" + Sdate + ".B.slc.par"
print(MFslcImg + " "+ MslcImg)
# Multi-aperture processing
call_str = 'sbi_filt '+ MslcImg + ' ' + MslcPar + ' '+SslcPar + ' ' + MFslcImg + ' '+ MFslcPar + ' ' + MBslcImg + ' ' + MBslcPar + ' ' + Squint
os.system(call_str)
print(call_str)
call_str = 'sbi_filt '+ SslcImg + ' ' + SslcPar + ' '+MslcPar + ' ' + SFslcImg + ' '+ SFslcPar + ' ' + SBslcImg + ' ' + SBslcPar + ' ' + Squint
os.system(call_str)
sys.exit(1)
if __name__ == '__main__':
main(sys.argv[:])
@@ -0,0 +1,180 @@
#! /usr/bin/env python
#'''
###################################################################################
# #
# Author: Yun-Meng Cao #
# Email : ymcmrs@gmail.com #
# Date : Mar, 2017 #
# #
# Select Interferometry-Pairs from time series SAR images #
# #
###################################################################################
#'''
import numpy as np
import os
import sys
import subprocess
import getopt
import time
import glob
def check_variable_name(path):
s=path.split("/")[0]
if len(s)>0 and s[0]=="$":
p0=os.getenv(s[1:])
path=path.replace(path.split("/")[0],p0)
return path
def read_template(File, delimiter='='):
'''Reads the template file into a python dictionary structure.
Input : string, full path to the template file
Output: dictionary, pysar template content
Example:
tmpl = read_template(KyushuT424F610_640AlosA.template)
tmpl = read_template(R1_54014_ST5_L0_F898.000.pi, ':')
'''
template_dict = {}
for line in open(File):
line = line.strip()
c = [i.strip() for i in line.split(delimiter, 1)] #split on the 1st occurrence of delimiter
if len(c) < 2 or line.startswith('%') or line.startswith('#'):
next #ignore commented lines or those without variables
else:
atrName = c[0]
atrValue = str.replace(c[1],'\n','').split("#")[0].strip()
atrValue = check_variable_name(atrValue)
template_dict[atrName] = atrValue
return template_dict
def is_number(s):
try:
int(s)
return True
except ValueError:
return False
def add_zero(s):
if len(s)==1:
s="000"+s
elif len(s)==2:
s="00"+s
elif len(s)==3:
s="0"+s
return s
def usage():
print('''
******************************************************************************************************
Select interferometry pairs from time series SAR images
usage:
SelectPairs_Gamma.py ProjectName
e.g. SelectPairs_Gamma.py PacayaT163TsxHhA
*******************************************************************************************************
''')
def main(argv):
if len(sys.argv)==2:
if argv[0] in ['-h','--help']: usage(); sys.exit(1)
else: projectName=sys.argv[1]
else:
usage();sys.exit(1)
scratchDir = os.getenv('SCRATCHDIR')
templateDir = os.getenv('TEMPLATEDIR')
templateFile = templateDir + "/" + projectName + ".template"
templateContents=read_template(templateFile)
processDir = scratchDir + '/' + projectName + "/PROCESS"
slcDir = scratchDir + '/' + projectName + "/SLC"
if not os.path.isdir(processDir):
call_str = 'mkdir ' + processDir
os.system(call_str)
if 'JOB' in templateContents: JOB = templateContents['JOB']
else: JOB = 'IFG'
INF=JOB
if INF=='IFG':
Suffix=['']
print("Time series interferograms will be processed!")
elif INF=='MAI':
Suffix=['.F','.B']
print("Time series multi-aperture interferograms will be processed!")
elif INF=='RSI':
Suffix=['.HF','.LF']
print("Time series range split-spectrum interferograms will be processed!")
else:
print("The folder name %s cannot be identified !" % igramDir)
usage();sys.exit(1)
# define files
SLC_Tab = processDir + "/SLC_Tab"
TS_Berp = processDir + "/TS_Berp"
TS_Itab = processDir + "/TS_Itab"
itab_type = '1'
pltflg = '0'
if 'Max_Spacial_Baseline' in templateContents: MaxSB=templateContents['Max_Spacial_Baseline']
else:
print("Max_Spacial_Baseline is not found in template!! ")
print("500m is chosen as the threshold for spatial baseline!")
MaxSB = '500'
if 'Max_Temporal_Baseline' in templateContents: MaxTB=templateContents['Max_Temporal_Baseline']
else:
print("Max_Temporal_Baseline is not found in template!! ")
print("500 days is chosen as the threshold for temporal baseline!")
MaxTB = '500'
# extract available SAR images slc and slc_par
ListSLC = os.listdir(slcDir)
Datelist = []
SLCfile = []
SLCParfile = []
print("All of the available SAR acquisition datelist is :")
for kk in range(len(ListSLC)):
if ( is_number(ListSLC[kk]) and len(ListSLC[kk])==6 ): # if SAR date number is 8, 6 should change to 8.
DD=ListSLC[kk]
Year=int(DD[0:2])
Month = int(DD[2:4])
Day = int(DD[4:6])
if ( 0 < Year < 20 and 0 < Month < 13 and 0 < Day < 32 ):
Datelist.append(ListSLC[kk])
print(ListSLC[kk])
DateDir = slcDir+'/'+ListSLC[kk]
SLC0 = glob.glob(DateDir+'/*slc')[0]
SLCPar0 = glob.glob(DateDir+'/*slc.par')[0]
str_slc = slcDir + "/" + ListSLC[kk] +"/" + ListSLC[kk] + ".slc"
str_slc_par = slcDir + "/" + ListSLC[kk] +"/" + ListSLC[kk] + ".slc.par"
call_str = 'mv ' + SLC0 + ' ' + str_slc
os.system(call_str)
call_str = 'mv ' + SLCPar0 + ' ' + str_slc_par
os.system(call_str)
SLCfile.append(str_slc)
SLCParfile.append(str_slc_par)
print("Change name of SLC file is done! ")
sys.exit(1)
if __name__ == '__main__':
main(sys.argv[:])
@@ -0,0 +1,83 @@
# OpenTopography DEM 下载使用示例
## 快速开始
### 1. 获取免费API Key
访问: https://opentopography.org/myOpenTopo
- 注册账户 (免费)
- 在 'My Account' 页面请求 API key
- API key 立即可用
### 2. 下载不同分辨率的 DEM
#### SRTM 30m (推荐)
```bash
python makedem.py -r 116/117/39/40 --dem-source srtm \
--opentopo-api-key YOUR_KEY \
--opentopo-dem-type SRTMGL1
```
#### SRTM 90m
```bash
python makedem.py -r 116/117/39/40 --dem-source srtm \
--opentopo-api-key YOUR_KEY \
--opentopo-dem-type SRTMGL3
```
#### NASADEM 30m
```bash
python makedem.py -r 116/117/39/40 --dem-source srtm \
--opentopo-api-key YOUR_KEY \
--opentopo-dem-type NASADEM
```
#### Copernicus 30m
```bash
python makedem.py -r 116/117/39/40 --dem-source srtm \
--opentopo-api-key YOUR_KEY \
--opentopo-dem-type COP30
```
#### Copernicus 90m
```bash
python makedem.py -r 116/117/39/40 --dem-source srtm \
--opentopo-api-key YOUR_KEY \
--opentopo-dem-type COP90
```
## 数据对比
| DEM类型 | 分辨率 | 覆盖范围 | 推荐用途 |
|---------|--------|----------|----------|
| **SRTMGL1** | **30m** | 60°S-60°N | **SRTM研究首选** |
| SRTMGL3 | 90m | 60°S-60°N | 快速预览 |
| **NASADEM** | **30m** | 60°S-60°N | **高精度研究** |
| **COP30** | **30m** | 全球 | **全球覆盖首选** |
| COP90 | 90m | 全球 | 快速预览 |
## 推荐选择
1. **SRTM研究**: SRTMGL1 (30m)
2. **高精度需求**: NASADEM 或 COP30 (30m)
3. **全球覆盖**: COP30 (30m)
4. **快速预览**: SRTMGL3 或 COP90 (90m)
## 注意事项
- **SRTMGL1/COP30/NASADEM** (30m): 最大支持 450,000 km²
- **SRTMGL3/COP90** (90m): 最大支持 4,050,000 km²
- 所有数据集需要 OpenTopography API key
- 免费配额足够大部分科研用途
## 输出文件命名
- SRTMGL1_116_117_39_40.tif
- NASADEM_116_117_39_40.tif
- COP30_116_117_39_40.tif
文件名格式: `{DEM类型}_{西经}_{东经}_{南纬}_{北纬}.tif`
---
**更新日期**: 2026-03-13
@@ -0,0 +1,394 @@
#! /usr/bin/env python
#################################################################
### This program is part of PyINT v2.1 ###
### Pixel Offset Tracking (POT) for a single pair ###
### Based on GAMMA offset_pwr_tracking / offset_pwr_tracking2###
### Author: ZYD / Cascade AI ###
#################################################################
import os
import sys
import time
import argparse
import numpy as np
from pyint import _utils as ut
INTRODUCTION = '''
-------------------------------------------------------------------
Pixel Offset Tracking (POT) for a single interferometric pair
using GAMMA software.
Two-round estimation approach (Greenland tracking demo):
Round 1: Large search window for initial offset field
Post-processing: Quality check, outlier removal, gap filling
Round 2: Smaller window with conditioned Round 1 as initial
Final: Convert pixel offsets to displacement in meters + Geocode
'''
EXAMPLE = '''
Usage:
POT_gamma.py projectName Mdate Sdate
POT_gamma.py shanghaiT171F128S1A 20241105 20241117
-------------------------------------------------------------------
'''
def run_cmd(cmd_str):
"""执行 GAMMA 命令并打印"""
print(f' >> {cmd_str}')
return os.system(cmd_str)
def sanitize_gamma_float(filepath, valid_max=1e6):
"""
清理 GAMMA 浮点数据文件中的无效值。
GAMMA 对无效像素写入特殊标记值(~3.4e38 / NaN / Inf),
这些值无法被 single_class_mapping 的范围过滤器正确捕获。
将 NaN / Inf / |val| > valid_max 的像素替换为 0.0。
"""
data = np.fromfile(filepath, dtype=np.float32)
bad_mask = ~np.isfinite(data) | (np.abs(data) > valid_max)
n_bad = int(np.sum(bad_mask))
if n_bad > 0:
data[bad_mask] = 0.0
data.tofile(filepath)
print(f' [sanitize] {os.path.basename(filepath)}: '
f'清理 {n_bad} 个无效像素 (NaN/Inf/|val|>{valid_max})')
def postprocess_offsets(offs_cpx, ccp, mli, width,
ccp_thresh, roff_min, roff_max,
azoff_min, azoff_max,
drange_thresh, dazimuth_thresh,
median_win, median_nmin,
prefix):
"""
偏移量场后处理流程(参考 GAMMA Greenland tracking demo):
1) 提取距离向/方位向分量 + 清理 GAMMA no-data 标记值
2) 初始掩膜: 互相关阈值 + 偏移量范围限制
3) 中值滤波 + 偏差计算
4) 偏差阈值精细掩膜
5) 空洞填充
6) 空间滤波 → 组合为 conditioned 复数偏移量
返回: (condi, real_interp, imag_interp)
- condi: fspf 平滑后的复数偏移量(供 Round 2 初始值)
- real_interp / imag_interp: 填充后的偏移量(供最终米制转换)
"""
real_file = prefix + '.real'
imag_file = prefix + '.imag'
# --- 1) 提取距离向 (real) 和方位向 (imag) ---
run_cmd(f'cpx_to_real {offs_cpx} {real_file} {width} 0')
run_cmd(f'cpx_to_real {offs_cpx} {imag_file} {width} 1')
# 清理 GAMMA no-data 标记值(~3.4e38),避免污染后续掩膜和插值
valid_max = max(abs(float(roff_max)), abs(float(roff_min)),
abs(float(azoff_max)), abs(float(azoff_min))) * 10
sanitize_gamma_float(real_file, valid_max)
sanitize_gamma_float(imag_file, valid_max)
sanitize_gamma_float(ccp, 1.0)
# --- 2) 初始掩膜: 互相关 + 偏移量范围 ---
mask1 = prefix + '.mask1.bmp'
real_m1 = prefix + '.real.masked1'
imag_m1 = prefix + '.imag.masked1'
run_cmd(f'single_class_mapping 3 '
f'{ccp} {ccp_thresh} 1.0 '
f'{real_file} {roff_min} {roff_max} '
f'{imag_file} {azoff_min} {azoff_max} '
f'{mask1} {width} 1 0 1 1')
run_cmd(f'mask_class {mask1} {real_file} {real_m1} 0 1 1 1 0 0.0')
run_cmd(f'mask_class {mask1} {imag_file} {imag_m1} 0 1 1 1 0 0.0')
# 初始掩膜后 BMP
run_cmd(f'rasdt_pwr {real_m1} {mli} {width} - - - - '
f'{roff_min} {roff_max} 0 rmg.cm {real_m1}.bmp - - 24')
run_cmd(f'rasdt_pwr {imag_m1} {mli} {width} - - - - '
f'{azoff_min} {azoff_max} 0 rmg.cm {imag_m1}.bmp - - 24')
# --- 3) 中值滤波 + 偏差 ---
real_med = prefix + '.real.median'
imag_med = prefix + '.imag.median'
dreal = prefix + '.dreal'
dimag = prefix + '.dimag'
run_cmd(f'median_filter {real_m1} {real_med} {width} '
f'{median_win} {median_win} {median_nmin}')
run_cmd(f'lin_comb 2 {real_m1} {real_med} 0. 1. -1. '
f'{dreal} {width} 1 0 1 1')
run_cmd(f'median_filter {imag_m1} {imag_med} {width} '
f'{median_win} {median_win} {median_nmin}')
run_cmd(f'lin_comb 2 {imag_m1} {imag_med} 0. 1. -1. '
f'{dimag} {width} 1 0 1 1')
# --- 4) 偏差阈值精细掩膜 ---
mask2 = prefix + '.mask2.bmp'
real_masked = prefix + '.real.masked'
imag_masked = prefix + '.imag.masked'
run_cmd(f'single_class_mapping 5 '
f'{dreal} -{drange_thresh} {drange_thresh} '
f'{dimag} -{dazimuth_thresh} {dazimuth_thresh} '
f'{ccp} {ccp_thresh} 1.0 '
f'{real_file} {roff_min} {roff_max} '
f'{imag_file} {azoff_min} {azoff_max} '
f'{mask2} {width} 1 0 1 1 5')
run_cmd(f'mask_class {mask2} {real_file} {real_masked} 0 1 1 1 0 0.0')
run_cmd(f'mask_class {mask2} {imag_file} {imag_masked} 0 1 1 1 0 0.0')
# 精细掩膜后 BMP
run_cmd(f'rasdt_pwr {real_masked} {mli} {width} - - - - '
f'{roff_min} {roff_max} 0 rmg.cm {real_masked}.bmp - - 24')
run_cmd(f'rasdt_pwr {imag_masked} {mli} {width} - - - - '
f'{azoff_min} {azoff_max} 0 rmg.cm {imag_masked}.bmp - - 24')
# --- 5) 空洞填充 ---
real_interp = prefix + '.real.interp'
imag_interp = prefix + '.imag.interp'
run_cmd(f'fill_gaps {real_masked} {width} {real_interp} 0 4 - 1')
run_cmd(f'fill_gaps {imag_masked} {width} {imag_interp} 0 4 - 1')
# 清理 fill_gaps 插值可能引入的 NaN/Inf/极端值
sanitize_gamma_float(real_interp, valid_max)
sanitize_gamma_float(imag_interp, valid_max)
# 填充后 BMP
run_cmd(f'rasdt_pwr {real_interp} {mli} {width} - - - - '
f'{roff_min} {roff_max} 0 rmg.cm {real_interp}.bmp - - 24')
run_cmd(f'rasdt_pwr {imag_interp} {mli} {width} - - - - '
f'{azoff_min} {azoff_max} 0 rmg.cm {imag_interp}.bmp - - 24')
# --- 6) 空间滤波 + 组合 conditioned ---
real_fspf = prefix + '.real.fspf'
imag_fspf = prefix + '.imag.fspf'
run_cmd(f'fspf {real_interp} {real_fspf} {width} 2 2 2')
run_cmd(f'fspf {imag_interp} {imag_fspf} {width} 2 2 2')
condi = prefix + '.condi'
run_cmd(f'real_to_cpx {real_fspf} {imag_fspf} {condi} {width} 0')
return condi, real_interp, imag_interp
def cmdLineParse():
parser = argparse.ArgumentParser(
description='Pixel Offset Tracking for a single pair using GAMMA.',
formatter_class=argparse.RawTextHelpFormatter,
epilog=INTRODUCTION + '\n' + EXAMPLE)
parser.add_argument('projectName', help='projectName for processing.')
parser.add_argument('Mdate', help='Master date.')
parser.add_argument('Sdate', help='Slave date.')
inps = parser.parse_args()
return inps
def main(argv):
start_time = time.time()
inps = cmdLineParse()
Mdate = inps.Mdate
Sdate = inps.Sdate
projectName = inps.projectName
scratchDir = os.getenv('SCRATCHDIR')
templateDir = os.getenv('TEMPLATEDIR')
templateFile = templateDir + '/' + projectName + '.template'
templateDict = ut.update_template(templateFile)
rlks = templateDict['range_looks']
azlks = templateDict['azimuth_looks']
masterDate = templateDict['masterDate']
# ========== POT 参数 ==========
pot_rstep = templateDict['pot_rstep']
pot_azstep = templateDict['pot_azstep']
pot_rwin = templateDict['pot_rwin']
pot_azwin = templateDict['pot_azwin']
pot_rwin2 = templateDict['pot_rwin2']
pot_azwin2 = templateDict['pot_azwin2']
pot_ovr = templateDict['pot_ovr']
pot_snr_thresh = templateDict['pot_snr_thresh']
pot_ccp_thresh = templateDict['pot_ccp_thresh']
pot_roff_min = templateDict['pot_roff_min']
pot_roff_max = templateDict['pot_roff_max']
pot_azoff_min = templateDict['pot_azoff_min']
pot_azoff_max = templateDict['pot_azoff_max']
pot_drange_thresh = templateDict['pot_drange_thresh']
pot_dazimuth_thresh = templateDict['pot_dazimuth_thresh']
pot_median_win = templateDict['pot_median_win']
pot_median_nmin = templateDict['pot_median_nmin']
pot_two_rounds = templateDict['pot_two_rounds']
pot_geocode = templateDict['pot_geocode']
pot_disp_max = templateDict['pot_disp_max']
# ========== 目录 ==========
projectDir = scratchDir + '/' + projectName
rslcDir = projectDir + '/RSLC'
demDir = projectDir + '/DEM'
potDir = projectDir + '/offsets'
if not os.path.isdir(potDir):
os.mkdir(potDir)
Pair = Mdate + '-' + Sdate
workDir = potDir + '/' + Pair
if not os.path.isdir(workDir):
os.mkdir(workDir)
# ========== 输入文件 ==========
Mrslc = rslcDir + '/' + Mdate + '/' + Mdate + '.rslc'
MrslcPar = rslcDir + '/' + Mdate + '/' + Mdate + '.rslc.par'
Srslc = rslcDir + '/' + Sdate + '/' + Sdate + '.rslc'
SrslcPar = rslcDir + '/' + Sdate + '/' + Sdate + '.rslc.par'
slc_width = ut.read_gamma_par(MrslcPar, 'read', 'range_samples')
off_width = str(int(int(slc_width) // int(pot_rstep)))
print('=' * 60)
print(f'Pixel Offset Tracking (POT): {Pair}')
print(f' SLC width : {slc_width}')
print(f' Offset width : {off_width}')
print(f' Step (r x az) : {pot_rstep} x {pot_azstep}')
print(f' R1 window : {pot_rwin} x {pot_azwin}')
if pot_two_rounds == '1':
print(f' R2 window : {pot_rwin2} x {pot_azwin2}')
print(f' Offset range : [{pot_roff_min}, {pot_roff_max}] r '
f'[{pot_azoff_min}, {pot_azoff_max}] az')
print('=' * 60)
#######################################################################
# Step 1: 生成偏移量几何下的 MLI(背景图 + 尺寸参考)
#######################################################################
print('\n[Step 1] 生成偏移量几何 MLI ...')
MLI_pot = workDir + '/' + Mdate + '.mli_pot'
MLI_pot_par = workDir + '/' + Mdate + '.mli_pot.par'
run_cmd(f'multi_look {Mrslc} {MrslcPar} {MLI_pot} {MLI_pot_par} '
f'{pot_rstep} {pot_azstep}')
run_cmd(f'raspwr {MLI_pot} {off_width} - - - - 1. .2 - {MLI_pot}.bmp')
#######################################################################
# Step 2: 创建偏移量参数文件
#######################################################################
print('\n[Step 2] 创建偏移量参数文件 ...')
OFF = workDir + '/' + Pair + '.off'
run_cmd(f'create_offset {MrslcPar} {SrslcPar} {OFF} 1 {rlks} {azlks} 0')
#######################################################################
# Step 3: Round 1 — 初始偏移量估计(大窗口)
#######################################################################
print(f'\n[Step 3] Round 1 偏移量估计 ({pot_rwin}x{pot_azwin}) ...')
r1_tag = f'{pot_rwin}x{pot_azwin}'
r1_prefix = workDir + '/' + Pair + '.offs' + r1_tag
offs_r1 = r1_prefix
ccp_r1 = workDir + '/' + Pair + '.ccp' + r1_tag
run_cmd(f'offset_pwr_tracking {Mrslc} {Srslc} {MrslcPar} {SrslcPar} '
f'{OFF} {offs_r1} {ccp_r1} '
f'{pot_rwin} {pot_azwin} - {pot_ovr} {pot_snr_thresh} '
f'{pot_rstep} {pot_azstep}')
#######################################################################
# Step 4: Round 1 后处理
#######################################################################
print(f'\n[Step 4] Round 1 后处理 ...')
r1_condi, _, _ = postprocess_offsets(
offs_cpx=offs_r1, ccp=ccp_r1, mli=MLI_pot, width=off_width,
ccp_thresh=pot_ccp_thresh,
roff_min=pot_roff_min, roff_max=pot_roff_max,
azoff_min=pot_azoff_min, azoff_max=pot_azoff_max,
drange_thresh=pot_drange_thresh, dazimuth_thresh=pot_dazimuth_thresh,
median_win=pot_median_win, median_nmin=pot_median_nmin,
prefix=r1_prefix)
# 默认使用 Round 1 结果
final_prefix = r1_prefix
final_ccp = ccp_r1
final_off = OFF
#######################################################################
# Step 5-6: Round 2 — 精细偏移量估计(小窗口,可选)
#######################################################################
if pot_two_rounds == '1':
print(f'\n[Step 5] Round 2 偏移量估计 ({pot_rwin2}x{pot_azwin2}) ...')
OFF2 = workDir + '/' + Pair + '.off2'
run_cmd(f'create_offset {MrslcPar} {SrslcPar} {OFF2} 1 {rlks} {azlks} 0')
r2_tag = f'{pot_rwin2}x{pot_azwin2}'
r2_prefix = workDir + '/' + Pair + '.offs' + r2_tag
offs_r2 = r2_prefix
ccp_r2 = workDir + '/' + Pair + '.ccp' + r2_tag
run_cmd(f'offset_pwr_tracking2 {Mrslc} {Srslc} {MrslcPar} {SrslcPar} '
f'{OFF2} {offs_r2} {ccp_r2} {OFF} {r1_condi} '
f'{pot_rwin2} {pot_azwin2} - {pot_ovr} {pot_snr_thresh} '
f'{pot_rstep} {pot_azstep}')
print(f'\n[Step 6] Round 2 后处理 ...')
_, _, _ = postprocess_offsets(
offs_cpx=offs_r2, ccp=ccp_r2, mli=MLI_pot, width=off_width,
ccp_thresh=pot_ccp_thresh,
roff_min=pot_roff_min, roff_max=pot_roff_max,
azoff_min=pot_azoff_min, azoff_max=pot_azoff_max,
drange_thresh=pot_drange_thresh, dazimuth_thresh=pot_dazimuth_thresh,
median_win=pot_median_win, median_nmin=pot_median_nmin,
prefix=r2_prefix)
final_prefix = r2_prefix
final_ccp = ccp_r2
final_off = OFF2
#######################################################################
# Step 7: 像素偏移量 → 米制位移量
#######################################################################
print('\n[Step 7] 像素偏移量转换为地面位移 (米) ...')
# 用填充后(非 fspf 平滑)的偏移量组合复数,供 offset_tracking 使用
final_real_interp = final_prefix + '.real.interp'
final_imag_interp = final_prefix + '.imag.interp'
final_offs_combined = final_prefix + '.offs_combined'
run_cmd(f'real_to_cpx {final_real_interp} {final_imag_interp} '
f'{final_offs_combined} {off_width} 0')
disp_map = workDir + '/' + Pair + '.disp_map'
run_cmd(f'offset_tracking {final_offs_combined} {final_ccp} '
f'{MrslcPar} {final_off} {disp_map} - 2 {pot_ccp_thresh} 0')
# 提取位移分量
disp_real = disp_map + '.real' # 地距向位移 (米)
disp_imag = disp_map + '.imag' # 方位向位移 (米)
disp_mag = disp_map + '.mag' # 位移幅值 (米)
run_cmd(f'cpx_to_real {disp_map} {disp_real} {off_width} 0')
run_cmd(f'cpx_to_real {disp_map} {disp_imag} {off_width} 1')
run_cmd(f'cpx_to_real {disp_map} {disp_mag} {off_width} 3')
# 清理 offset_tracking 输出中的 NaN/Inf/极端值
disp_max_m = float(pot_disp_max) * 10
sanitize_gamma_float(disp_real, disp_max_m)
sanitize_gamma_float(disp_imag, disp_max_m)
sanitize_gamma_float(disp_mag, disp_max_m)
# BMP 可视化
run_cmd(f'rasdt_pwr {disp_real} {MLI_pot} {off_width} - - - - '
f'-{pot_disp_max} {pot_disp_max} 1 rmg.cm {disp_real}.bmp - - 24')
run_cmd(f'rasdt_pwr {disp_imag} {MLI_pot} {off_width} - - - - '
f'-{pot_disp_max} {pot_disp_max} 1 rmg.cm {disp_imag}.bmp - - 24')
run_cmd(f'rasdt_pwr {disp_mag} {MLI_pot} {off_width} - - - - '
f'-{pot_disp_max} {pot_disp_max} 1 rmg.cm {disp_mag}.bmp - - 24')
# 注意: 地理编码已移至 geocode_gamma.py --type pot
# 用法: geocode_gamma.py projectName Pair --type pot
print(f"\nPixel Offset Tracking for {Pair} is done!")
ut.print_process_time(start_time, time.time())
sys.exit(0)
if __name__ == '__main__':
main(sys.argv[:])
@@ -0,0 +1,148 @@
#! /usr/bin/env python
#################################################################
### This program is part of PyINT v2.1 ###
### Batch Pixel Offset Tracking (POT) using GAMMA ###
### Author: ZYD / Cascade AI ###
#################################################################
import numpy as np
import os
import sys
import getopt
import time
import glob
import argparse
import subprocess
from pyint import _utils as ut
def work(data0):
cmd = data0[0]
err_file = data0[1]
p = subprocess.run(cmd, shell=False, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
stdout = p.stdout
stderr = p.stderr
if type(stderr) == bytes:
aa = stderr.decode("utf-8")
else:
aa = stderr
if aa:
str0 = ' '.join(cmd) + '\n'
with open(err_file, 'a') as f:
f.write(str0)
f.write(aa)
f.write('\n')
return
#########################################################################
INTRODUCTION = '''
-------------------------------------------------------------------
Batch Pixel Offset Tracking for one project using GAMMA.
Runs POT_gamma.py for each interferometric pair in parallel.
Skips pairs that already have completed results (disp_map.mag.bmp).
'''
EXAMPLE = '''
Usage:
POT_gamma_all.py projectName
POT_gamma_all.py projectName --parallel 4
POT_gamma_all.py projectName --parallel 4 --ifgarmList-txt /test/ifgram_list.txt
-------------------------------------------------------------------
'''
def cmdLineParse():
parser = argparse.ArgumentParser(
description='Batch Pixel Offset Tracking for one project using GAMMA.',
formatter_class=argparse.RawTextHelpFormatter,
epilog=INTRODUCTION + '\n' + EXAMPLE)
parser.add_argument('projectName', help='projectName for processing.')
parser.add_argument('--parallel', dest='parallelNumb', type=int, default=1,
help='Enable parallel processing and specify the number of processors.')
parser.add_argument('--ifgarmList-txt', dest='ifgarmListTxt',
help='Provided ifgram_list_txt. Default: using ifgram_list.txt under projectName folder.')
inps = parser.parse_args()
return inps
def main(argv):
start_time = time.time()
inps = cmdLineParse()
projectName = inps.projectName
scratchDir = os.getenv('SCRATCHDIR')
templateDir = os.getenv('TEMPLATEDIR')
templateFile = templateDir + "/" + projectName + ".template"
projectDir = scratchDir + '/' + projectName
potDir = projectDir + '/offsets'
if not os.path.isdir(potDir):
os.mkdir(potDir)
templateDict = ut.update_template(templateFile)
rlks = templateDict['range_looks']
azlks = templateDict['azimuth_looks']
if inps.ifgarmListTxt:
ifgramList_txt = inps.ifgarmListTxt
else:
ifgramList_txt = projectDir + '/ifgram_list.txt'
ifgList0 = ut.read_txt2array(ifgramList_txt)
if len(ifgList0) == 3:
ifgList = ifgList0[0]
ifgList = [ifgList]
else:
ifgList = ifgList0[:, 0]
err_txt = projectDir + '/POT_gamma_all.err'
if os.path.isfile(err_txt):
os.remove(err_txt)
data_para = []
skip_count = 0
for i in range(len(ifgList)):
m0 = ut.yyyymmdd(ifgList[i].split('-')[0])
s0 = ut.yyyymmdd(ifgList[i].split('-')[1])
cmd0 = ['POT_gamma.py', projectName, m0, s0]
# 检查完成标志: disp_map.mag.bmp
Pair = ifgList[i]
disp_bmp = potDir + '/' + Pair + '/' + Pair + '.disp_map.mag.bmp'
k00 = 0
if os.path.isfile(disp_bmp):
if os.path.getsize(disp_bmp) > 0:
k00 = 1
skip_count += 1
if k00 == 0:
data0 = [cmd0, err_txt]
data_para.append(data0)
total = len(ifgList)
todo = len(data_para)
print(f'Pixel Offset Tracking: {total} pairs total, '
f'{skip_count} already done, {todo} to process')
print(f'Parallel processors: {inps.parallelNumb}')
print(f'Output directory: {potDir}')
print('=' * 60)
if todo > 0:
ut.parallel_process(data_para, work, n_jobs=inps.parallelNumb, use_kwargs=False)
print("Pixel Offset Tracking for project %s is done! " % projectName)
ut.print_process_time(start_time, time.time())
sys.exit(0)
if __name__ == '__main__':
main(sys.argv[:])
@@ -0,0 +1,26 @@
## GACOS CORRECTION FOR GMTSAR
These software is intended to correct unwrapped phases using GACOS grids for GMTSAR.
They have been tested with: GMT v6.1.0 GMTSAR v6.0
On "Test_against_matlab" folder, I perform comparisons with matlab with consistent results.
To reproduce the output just use: source command.txt in each folder.
There is a small README file in each folder
### SINGLE INTERFEROGRAM
single_GACOS_correction.csh is intented to correct a single interferogram at a time with certain parameters
### STACK OF INTERFEROGRAMS
GACOS_correction.csh and operation.csh are used to correct a stack of interferograms in a time series process
Corrections are applied to the unwrap.grd files
Feel free to use and edit the code if needed
References:
*Yu, C., Li, Z., Penna, N. T., & Crippa, P. (2018). Generic atmospheric correction model for Interferometric Synthetic Aperture Radar observations. Journal of Geophysical Research: Solid Earth, 123(10), 9202-9222.*
*Yu, C., Li, Z., & Penna, N. T. (2018). Interferometric synthetic aperture radar atmospheric correction using a GPS-based iterative tropospheric decomposition model. Remote Sensing of Environment, 204, 109-121.*
*Yu, C., Penna, N. T., & Li, Z. (2017). Generation of real‐time mode high‐resolution water vapor fields from GPS observations. Journal of Geophysical Research: Atmospheres, 122(3), 2008-2025.*
@@ -0,0 +1,216 @@
#! /usr/bin/env python
#'''
###################################################################################
# #
# Author: Yun-Meng Cao #
# Email : ymcmrs@gmail.com #
# Date : March , 2017 #
# #
# Range Split Spectrum for SAR complex data based on GAMMA #
# #
###################################################################################
#'''
import numpy as np
import os
import pysar._readfile as readfile
import sys
import subprocess
import getopt
import time
import glob
def check_variable_name(path):
s=path.split("/")[0]
if len(s)>0 and s[0]=="$":
p0=os.getenv(s[1:])
path=path.replace(path.split("/")[0],p0)
return path
def read_template(File, delimiter='='):
'''Reads the template file into a python dictionary structure.
Input : string, full path to the template file
Output: dictionary, pysar template content
Example:
tmpl = read_template(KyushuT424F610_640AlosA.template)
tmpl = read_template(R1_54014_ST5_L0_F898.000.pi, ':')
'''
template_dict = {}
for line in open(File):
line = line.strip()
c = [i.strip() for i in line.split(delimiter, 1)] #split on the 1st occurrence of delimiter
if len(c) < 2 or line.startswith('%') or line.startswith('#'):
next #ignore commented lines or those without variables
else:
atrName = c[0]
atrValue = str.replace(c[1],'\n','').split("#")[0].strip()
atrValue = check_variable_name(atrValue)
template_dict[atrName] = atrValue
return template_dict
def ras2jpg(input, strTitle):
call_str = "convert " + input + ".ras " + input + ".jpg"
os.system(call_str)
call_str = "convert " + input + ".jpg -resize 250 " + input + ".thumb.jpg"
os.system(call_str)
call_str = "convert " + input + ".jpg -resize 500 " + input + ".bthumb.jpg"
os.system(call_str)
call_str = "$INT_SCR/addtitle2jpg.pl " + input + ".thumb.jpg 14 " + strTitle
os.system(call_str)
call_str = "$INT_SCR/addtitle2jpg.pl " + input + ".bthumb.jpg 24 " + strTitle
os.system(call_str)
def UseGamma(inFile, task, keyword):
if task == "read":
f = open(inFile, "r")
while 1:
line = f.readline()
if not line: break
if line.count(keyword) == 1:
strtemp = line.split(":")
value = strtemp[1].strip()
return value
print("Keyword " + keyword + " doesn't exist in " + inFile)
f.close()
def geocode(inFile, outFile, UTMTORDC, nWidth, nWidthUTMDEM, nLineUTMDEM):
if inFile.rsplit('.')[1] == 'int':
call_str = '$GAMMA_BIN/geocode_back ' + inFile + ' ' + nWidth + ' ' + UTMTORDC + ' ' + outFile + ' ' + nWidthUTMDEM + ' ' + nLineUTMDEM + ' 0 1'
else:
call_str = '$GAMMA_BIN/geocode_back ' + inFile + ' ' + nWidth + ' ' + UTMTORDC + ' ' + outFile + ' ' + nWidthUTMDEM + ' ' + nLineUTMDEM + ' 0 0'
os.system(call_str)
def createBlankFile(strFile):
f = open(strFile,'w')
for i in range (10):
f.write('\n')
f.close()
def usage():
print('''
******************************************************************************************************
Split Spectrum on range direction to generate high-frequency- and low-frequency- SLCs
usage:
RSI_SLC_Gamma.py igramDir
e.g. RSI_SLC_Gamma.py RSI_PacayaT163TsxHhA_131021-131101_0011_-0007
*******************************************************************************************************
''')
def main(argv):
if len(sys.argv)==2:
if argv[0] in ['-h','--help']: usage(); sys.exit(1)
else: igramDir=sys.argv[1]
else:
usage();sys.exit(1)
INF = igramDir.split('_')[0]
projectName = igramDir.split('_')[1]
IFGPair = igramDir.split(projectName+'_')[1].split('_')[0]
Mdate = IFGPair.split('-')[0]
Sdate = IFGPair.split('-')[1]
scratchDir = os.getenv('SCRATCHDIR')
templateDir = os.getenv('TEMPLATEDIR')
templateFile = templateDir + "/" + projectName + ".template"
processDir = scratchDir + '/' + projectName + "/PROCESS"
slcDir = scratchDir + '/' + projectName + "/SLC"
workdir = processDir + '/' + igramDir
templateContents=read_template(templateFile)
rlks = templateContents['Range_Looks']
azlks = templateContents['Azimuth_Looks']
if INF!='RSI':
usage();sys.exit(1)
if not os.path.isdir(workdir):
call_str = 'mkdir ' + workdir
os.system(call_str)
SslcDir = slcDir + "/" + Sdate
MslcDir = slcDir + "/" + Mdate
# input slcs
SslcDir = slcDir + "/" + Sdate
MslcDir = slcDir + "/" + Mdate
MslcImg = MslcDir + "/" + Mdate + ".slc"
MslcPar = MslcDir + "/" + Mdate + ".slc.par"
SslcImg = SslcDir + "/" + Sdate + ".slc"
SslcPar = SslcDir + "/" + Sdate + ".slc.par"
MHslcImg = workdir + '/'+Mdate + '.HF.slc'
MHslcPar = workdir + '/'+Mdate + '.HF.slc.par'
call_str = 'cp ' + MslcPar + ' '+ MHslcPar
os.system(call_str)
SHslcImg = workdir + '/'+Sdate + '.HF.slc'
SHslcPar = workdir + '/'+Sdate + '.HF.slc.par'
call_str = 'cp ' + SslcPar + ' '+ SHslcPar
os.system(call_str)
MLslcImg = workdir + '/'+Mdate + '.LF.slc'
MLslcPar = workdir + '/'+Mdate + '.LF.slc.par'
call_str = 'cp ' + MslcPar + ' '+ MLslcPar
os.system(call_str)
SLslcImg = workdir + '/'+Sdate + '.LF.slc'
SLslcPar = workdir + '/'+Sdate + '.LF.slc.par'
call_str = 'cp ' + SslcPar + ' '+ SLslcPar
os.system(call_str)
nWidth = UseGamma(MslcPar, 'read','range_samples:')
call_str= 'bpf ' + MslcImg + ' ' + MHslcImg + ' ' + nWidth + ' 0.25 0.5 0 1 0 0 - - 1'
os.system(call_str)
call_str= 'bpf ' + MslcImg + ' ' + MLslcImg + ' ' + nWidth + ' -0.25 0.5 0 1 0 0 - - 1'
os.system(call_str)
nWidth = UseGamma(SslcPar, 'read','range_samples:')
call_str= 'bpf ' + SslcImg + ' ' + SHslcImg + ' ' + nWidth + ' 0.25 0.5 0 1 0 0 - - 1'
os.system(call_str)
call_str= 'bpf ' + SslcImg + ' ' + SLslcImg + ' ' + nWidth + ' -0.25 0.5 0 1 0 0 - - 1'
os.system(call_str)
print("Split spectrum for both slave and master date is done!")
sys.exit(1)
if __name__ == '__main__':
main(sys.argv[:])
@@ -0,0 +1,306 @@
#! /usr/bin/env python
#'''
##################################################################################
# #
# Author: Yun-Meng Cao #
# Email : ymcmrs@gmail.com #
# Date : June, 2019 #
# #
# Generate SLC from SAR_IMS_P1 data #
# #
##################################################################################
#'''
import numpy as np
import os
import sys
import subprocess
import getopt
import time
import glob
def check_variable_name(path):
s=path.split("/")[0]
if len(s)>0 and s[0]=="$":
p0=os.getenv(s[1:])
path=path.replace(path.split("/")[0],p0)
return path
def read_template(File, delimiter='='):
'''Reads the template file into a python dictionary structure.
Input : string, full path to the template file
Output: dictionary, pysar template content
Example:
tmpl = read_template(KyushuT424F610_640AlosA.template)
tmpl = read_template(R1_54014_ST5_L0_F898.000.pi, ':')
'''
template_dict = {}
for line in open(File):
line = line.strip()
c = [i.strip() for i in line.split(delimiter, 1)] #split on the 1st occurrence of delimiter
if len(c) < 2 or line.startswith('%') or line.startswith('#'):
next #ignore commented lines or those without variables
else:
atrName = c[0]
atrValue = str.replace(c[1],'\n','').split("#")[0].strip()
atrValue = check_variable_name(atrValue)
template_dict[atrName] = atrValue
return template_dict
def UseGamma(inFile, task, keyword):
if task == "read":
f = open(inFile, "r")
while 1:
line = f.readline()
if not line: break
if line.count(keyword) == 1:
strtemp = line.split(":")
value = strtemp[1].strip()
return value
print("Keyword " + keyword + " doesn't exist in " + inFile)
f.close
def rm(TXT):
call_str = 'rm ' + TXT
os.system(call_str)
def usage():
print('''
******************************************************************************************************
Generate SLC and SLC_par file for ERS/ENVISAT (SAR_IMS_1P format)
usage:
Down2SLC_ERS.py ProjectName DownName
e.g. Down2SLC_ERS.py CotopaxiT120ERSA 910101
*******************************************************************************************************
''')
def main(argv):
if len(sys.argv)==3:
projectName = sys.argv[1]
Date = sys.argv[2]
else:
usage();sys.exit(1)
scratchDir = os.getenv('SCRATCHDIR')
templateDir = os.getenv('TEMPLATEDIR')
templateFile = templateDir + '/' + projectName + '.template'
templateContents=read_template(templateFile)
if 'rlks4cor' in templateContents: rlks4cor = templateContents['rlks4cor']
else: rlks4cor = '4'
if 'azlks4cor' in templateContents: azlks4cor = templateContents['azlks4cor']
else: azlks4cor = '4'
if 'rwin4cor' in templateContents: rwin4cor = templateContents['rwin4cor']
else: rwin4cor = '128'
if 'azwin4cor' in templateContents: azwin4cor = templateContents['azwin4cor']
else: azwin4cor = '128'
if 'rsample4cor' in templateContents: rsample4cor = templateContents['rsample4cor']
else: rsample4cor = '64'
if 'azsample4cor' in templateContents: azsample4cor = templateContents['azsample4cor']
else: azsample4cor = '64'
if ' rpos4cor' in templateContents: rpos4cor = templateContents[' rpos4cor']
else: rpos4cor = ' - '
if 'azpos4cor' in templateContents: azpos4cor = templateContents['azpos4cor']
else: azpos4cor = ' - '
if 'rfwin4cor' in templateContents: rfwin4cor = templateContents['rfwin4cor']
else: rfwin4cor = str(int(int(rwin4cor)/2))
if 'azfwin4cor' in templateContents: azfwin4cor = templateContents['azfwin4cor']
else: azfwin4cor = str(int(int(azwin4cor)/2))
if 'rfsample4cor' in templateContents: rfsample4cor = templateContents['rfsample4cor']
else: rfsample4cor = str(2*int(rsample4cor))
if 'azfsample4cor' in templateContents: azfsample4cor = templateContents['azfsample4cor']
else: azfsample4cor = str(2*int(azsample4cor))
if 'thresh4cor' in templateContents: thresh4cor = templateContents['thresh4cor']
else: thresh4cor = ' 0.2 '
rlks = templateContents['Range_Looks']
azlks = templateContents['Azimuth_Looks']
projectDir = scratchDir + '/' + projectName
downDir = scratchDir + '/' + projectName + "/DOWNLOAD"
slcDir = scratchDir + '/' + projectName + '/SLC'
if not os.path.isdir(slcDir):
call_str= 'mkdir ' +slcDir
os.system(call_str)
os.chdir(downDir)
t0 = 't0_' + Date
call_str = 'ls >' + t0
os.system(call_str)
tt = 'tt_' + Date
call_str = "grep " + Date + ' ' + t0 + '> ' + tt
os.system(call_str)
te = 'te_' + Date
call_str = "grep SAR_IM " + tt + " > " + te
os.system(call_str)
AA= np.loadtxt(te,dtype=np.str)
Na = AA.size
AA=AA.reshape(Na,)
for i in range(Na):
Date0 = Date+'_' + str(i)
downName = str(AA[i])
FileDir = downDir + '/' + downName
call_str = 'raw2slc_ers_envisat.py '+ FileDir + ' -o ' + Date0
os.system(call_str)
#call_str ="rename 's/VV.SLC/slc/g' *"
#os.system(call_str)
#slcpar = Date0 + '.slc.par'
#call_str = 'ERS_orb_cor_par.py ' + slcpar
#os.system(call_str)
Date0 = Date
if len(Date)==6:
Date6 = Date
Date0 = Date
elif len(Date)==8:
Date0 = Date[2:8]
Date6 = Date[2:8]
else:
print('The input Date is invalid.')
sys.exit(1)
dataDir = slcDir + '/' + Date0
if not os.path.isdir(dataDir):
call_str = 'mkdir ' + dataDir
print('Generate SLC dir for date: ' + Date0)
os.system(call_str)
call_str = 'mv ' + Date + '*.slc* ' + dataDir
os.system(call_str)
os.chdir(dataDir)
for i in range(Na):
Date0 = Date+'_' + str(i)
downName = str(AA[i])
SLCm = Date0 + '.slc'
SLCm_par = Date0 + '.slc.par'
MamprlksImg = Date0 + '.amp'
MamprlksPar = Date0 + '.amp.par'
call_str = 'multi_look ' + SLCm + ' ' + SLCm_par + ' ' + MamprlksImg + ' ' + MamprlksPar + ' ' + rlks + ' ' + azlks
os.system(call_str)
nWidth = UseGamma(MamprlksPar, 'read', 'range_samples')
call_str = 'raspwr ' + MamprlksImg + ' ' + nWidth
os.system(call_str)
SLC = Date6+'.slc'
SLCPAR = Date6 + '.slc.par'
AMP = Date6+'.amp'
AMPPAR = Date6+'.amp.par'
if Na==1:
os.rename(SLCm,SLC)
os.rename(SLCm_par,SLCPAR)
os.rename(MamprlksImg,AMP)
os.rename(MamprlksPar,AMPPAR)
for i in range(Na-1):
if i==0:
DateA = Date + '_0'
else:
DateA = Date + '_' + str(i-1) + str(i)
SLCA = DateA + '.slc'
SLCA_par = DateA + '.slc.par'
DateB = Date + '_' +str(i+1)
SLCB = DateB + '.slc'
SLCB_par = DateB + '.slc.par'
DateC = Date + '_' + str(i) + str(i+1)
SLCC = DateC + '.slc'
SLCC_par = DateC + '.slc.par'
#####################################################################################
MamprlksImg = Date + '.amp'
MamprlksPar = Date + '.amp.par'
off = DateC + '.off'
offs = DateC + '.offs'
offsets = DateC + '.offsets'
coffs = DateC + '.coffs'
coffsets = DateC + '.coffsets'
snr = DateC + '.snr'
off_std = DateC + '.off_std'
########################## Generate off file #############################
call_str = "create_offset " + SLCA_par + " " + SLCB_par + " " + off + " 1 - - 0"
os.system(call_str)
call_str = 'init_offset_orbit '+ SLCA_par + " " + SLCB_par + ' ' + off
os.system(call_str)
call_str = 'init_offset '+ SLCA + ' ' + SLCB + ' ' + SLCA_par + ' ' + SLCB_par + ' ' + off + ' ' + rlks4cor + ' ' + azlks4cor + ' ' + rpos4cor + ' ' + azpos4cor
os.system(call_str)
call_str = 'init_offset '+ SLCA + ' ' + SLCB + ' ' + SLCA_par + ' ' + SLCB_par + ' ' + off + ' 1 1 - - '
os.system(call_str)
call_str = "offset_pwr " + SLCA + " " + SLCB + " " + SLCA_par + " " + SLCB_par + " " + off + " " + offs + " " + snr + " " + rwin4cor + " " + azwin4cor + " " + offsets + " 2 "+ rsample4cor + " " + azsample4cor
os.system(call_str)
call_str = "offset_fit " + offs + " " + snr + " " + off + " " + coffs + " " + coffsets + " " + thresh4cor +" 3"
os.system(call_str)
call_str = "offset_pwr " +SLCA + " " + SLCB + " " + SLCA_par + " " + SLCB_par + " " + off + " " + offs + " " + snr + " " + rfwin4cor + " " + azfwin4cor + " " + offsets + " 2 " + rfsample4cor + " " + azfsample4cor
os.system(call_str)
call_str = "offset_fit " + offs + " " + snr + " " + off + " " + coffs + " " + coffsets + " " + thresh4cor + " 4 >" + off_std
os.system(call_str)
########################################################################################
call_str = 'SLC_cat ' + SLCA + ' ' + SLCB + ' ' + SLCA_par + ' ' + SLCB_par + ' ' + off + ' ' + SLCC + ' ' + SLCC_par
os.system(call_str)
if i==(Na-2):
if len(Date)==6:
DD = Date
else:
DD = Date[2:8]
SLCm = DD + '.slc'
SLCm_par = DD + '.slc.par'
call_str = 'cp ' + SLCC + ' ' + SLCm
os.system(call_str)
call_str = 'cp ' + SLCC_par + ' ' + SLCm_par
os.system(call_str)
call_str = 'multi_look ' + SLCm + ' ' + SLCm_par + ' ' + MamprlksImg + ' ' + MamprlksPar + ' ' + rlks + ' ' + azlks
os.system(call_str)
nWidth = UseGamma(MamprlksPar, 'read', 'range_samples')
call_str = 'raspwr ' + MamprlksImg + ' ' + nWidth
os.system(call_str)
call_str = 'rm *.amp'
os.system(call_str)
call_str = 'rm *_*.slc'
os.system(call_str)
print("Down to SLC for %s is done! " % Date)
sys.exit(1)
if __name__ == '__main__':
main(sys.argv[:])
@@ -0,0 +1,136 @@
#! /usr/bin/env python
#'''
##################################################################################
# #
# Author: Yun-Meng Cao #
# Email : ymcmrs@gmail.com #
# Date : March, 2017 #
# #
# Generate Sentinel SLC from the downloaded data #
# #
##################################################################################
#'''
import numpy as np
import os
import sys
import subprocess
import getopt
import time
import glob
def check_variable_name(path):
s=path.split("/")[0]
if len(s)>0 and s[0]=="$":
p0=os.getenv(s[1:])
path=path.replace(path.split("/")[0],p0)
return path
def read_template(File, delimiter='='):
'''Reads the template file into a python dictionary structure.
Input : string, full path to the template file
Output: dictionary, pysar template content
Example:
tmpl = read_template(KyushuT424F610_640AlosA.template)
tmpl = read_template(R1_54014_ST5_L0_F898.000.pi, ':')
'''
template_dict = {}
for line in open(File):
line = line.strip()
c = [i.strip() for i in line.split(delimiter, 1)] #split on the 1st occurrence of delimiter
if len(c) < 2 or line.startswith('%') or line.startswith('#'):
next #ignore commented lines or those without variables
else:
atrName = c[0]
atrValue = str.replace(c[1],'\n','').split("#")[0].strip()
atrValue = check_variable_name(atrValue)
template_dict[atrName] = atrValue
return template_dict
def UseGamma(inFile, task, keyword):
if task == "read":
f = open(inFile, "r")
while 1:
line = f.readline()
if not line: break
if line.count(keyword) == 1:
strtemp = line.split(":")
value = strtemp[1].strip()
return value
print("Keyword " + keyword + " doesn't exist in " + inFile)
f.close
def rm(TXT):
call_str = 'rm ' + TXT
os.system(call_str)
def usage():
print('''
******************************************************************************************************
Cat ERS SLC from ERS raw data with ENVISAT format.
usage:
Raw2SLC_ERS_Cat_All.py ProjectName
e.g. Raw2SLC_ERS_Cat_All.py CotopaxiT120ERSA
*******************************************************************************************************
''')
def main(argv):
if len(sys.argv)==2:
projectName = sys.argv[1]
else:
usage();sys.exit(1)
scratchDir = os.getenv('SCRATCHDIR')
templateDir = os.getenv('TEMPLATEDIR')
projectDir = scratchDir + '/' + projectName
downDir = scratchDir + '/' + projectName + "/DOWNLOAD"
slcDir = scratchDir + '/' + projectName + '/SLC'
if not os.path.isdir(slcDir):
call_str= 'mkdir ' +slcDir
os.system(call_str)
os.chdir(downDir)
call_str = 'ls > tt0'
os.system(call_str)
call_str = 'grep SAR_IM tt0 >tt1'
os.system(call_str)
call_str = "awk -F0PWDSI '{print $2}' tt1 > tt2 "
os.system(call_str)
call_str = "awk -F_ '{print $1}' tt2 > ttt"
os.system(call_str)
call_str = 'sort ttt | uniq > ttm'
os.system(call_str)
AA= np.loadtxt('ttm',dtype=np.str)
Na = AA.size
for i in range(Na):
call_str = 'Raw2SLC_ERS_Cat.py ' + projectName + ' ' + AA[i]
print(call_str)
call_str = 'Raw2SLC_ERS_Cat.py ' + projectName + ' ' + AA[i] + ' >/dev/null'
os.system(call_str)
print("Down to SLC for %s is done! " % projectName)
sys.exit(1)
if __name__ == '__main__':
main(sys.argv[:])
@@ -0,0 +1,144 @@
#! /usr/bin/env python
#'''
##################################################################################
### Author: Yun-Meng Cao ###
### Date : March, 2017 ###
### Email : ymcmrs@gmail.com ###
### Transform SAR coordinates into LAT/LON coordinates based on lookup table ###
##################################################################################
#'''
import os
import sys
import glob
import time
import argparse
import h5py
import numpy as np
def check_variable_name(path):
s=path.split("/")[0]
if len(s)>0 and s[0]=="$":
p0=os.getenv(s[1:])
path=path.replace(path.split("/")[0],p0)
return path
def read_template(File, delimiter='='):
'''Reads the template file into a python dictionary structure.
Input : string, full path to the template file
Output: dictionary, pysar template content
Example:
tmpl = read_template(KyushuT424F610_640AlosA.template)
tmpl = read_template(R1_54014_ST5_L0_F898.000.pi, ':')
'''
template_dict = {}
for line in open(File):
line = line.strip()
c = [i.strip() for i in line.split(delimiter, 1)] #split on the 1st occurrence of delimiter
if len(c) < 2 or line.startswith('%') or line.startswith('#'):
next #ignore commented lines or those without variables
else:
atrName = c[0]
atrValue = str.replace(c[1],'\n','').split("#")[0].strip()
atrValue = check_variable_name(atrValue)
template_dict[atrName] = atrValue
return template_dict
def read_data(inFile, dtype, nWidth, nLength):
data = np.fromfile(inFile, dtype, int(nLength)*int(nWidth)).reshape(int(nLength),int(nWidth))
return data
def is_number(s):
try:
int(s)
return True
except ValueError:
return False
def add_zero(s):
if len(s)==1:
s="000"+s
elif len(s)==2:
s="00"+s
elif len(s)==3:
s="0"+s
return s
def UseGamma(inFile, task, keyword):
if task == "read":
f = open(inFile, "r")
while 1:
line = f.readline()
if not line: break
if line.count(keyword) == 1:
strtemp = line.split(":")
value = strtemp[1].strip()
return value
print("Keyword " + keyword + " doesn't exist in " + inFile)
f.close()
def usage():
print('''
******************************************************************************************************
Transform SAR coordinates into LAT/LON coordinates based on lookup table
usage:
SAR2LATLON.py Range Azimuth LookupTableFile UTMDEMpar
e.g. SAR2LATLON.py 1500 1000 /Yunmeng/20201230.utm_to_rdc /Yunmeng/20201230.dem.utm.par
*******************************************************************************************************
''')
def main(argv):
if len(sys.argv)==5:
Range = sys.argv[1]
Azimuth = sys.argv[2]
LtFile = sys.argv[3]
UTMPAR = sys.argv[4]
else:
usage();sys.exit(1)
nWidthUTM = UseGamma(UTMPAR, 'read', 'width:')
nLineUTM = UseGamma(UTMPAR, 'read', 'nlines:')
Corner_LAT = UseGamma(UTMPAR, 'read', 'corner_lat:')
Corner_LON = UseGamma(UTMPAR, 'read', 'corner_lon:')
Corner_LAT =Corner_LAT.split(' ')[0]
Corner_LON =Corner_LON.split(' ')[0]
post_Lat = UseGamma(UTMPAR, 'read', 'post_lat:')
post_Lon = UseGamma(UTMPAR, 'read', 'post_lon:')
post_Lat =post_Lat.split(' ')[0]
post_Lon =post_Lon.split(' ')[0]
data = read_data(LtFile,'>c8',nWidthUTM,nLineUTM) # real: range imaginary: azimuth
Range_LT = data.real
Azimuth_LT = data.imag
CPX_input =complex(Range + '+' + Azimuth+'j')
DD = abs(CPX_input - data)
LL= abs(DD)
IDX= np.where(LL == LL.min())
Lat_out = float(Corner_LAT) + IDX[0]*float(post_Lat)
Lon_out = float(Corner_LON) + IDX[1]*float(post_Lon)
print(' Range: ' + Range + ' ' + 'Azimuth: ' + Azimuth)
print(' Latitude: ' + str(Lat_out[0]) + ' ' + 'Longitude: ' + str(Lon_out[0]))
##############################################################################
if __name__ == '__main__':
main(sys.argv[1:])
@@ -0,0 +1,150 @@
# SRTM 自动下载功能说明
## 功能概述
`makedem.py` 现在支持自动下载SRTM数据,无需手动准备数据文件!
## 使用方法
### 方法1: 自动下载 (推荐)
**步骤1: 获取OpenTopography API key** (免费)
访问: https://opentopography.org/myOpenTopo
- 注册免费账户
- 在 'My Account' 页面请求API key
- API key立即可用,免费配额足够大部分用途
**步骤2: 运行命令**
```bash
# 使用API key自动下载SRTM数据
python makedem.py -r 116/117/39/40 --dem-source srtm --opentopo-api-key YOUR_API_KEY
# 或设置环境变量
export OPENTOPO_API_KEY="your_api_key_here"
python makedem.py -r 116/117/39/40 --dem-source srtm
```
### 方法2: 使用预下载的.hgt文件
如果已有SRTM .hgt文件:
```bash
python makedem.py -r 116/117/39/40 --dem-source srtm --srtm-data-dir /path/to/srtm_data
```
## SRTM数据规格
- **分辨率**: 90米 (SRTM GL3)
- **覆盖**: 全球 (60°S - 60°N)
- **数据源**: OpenTopography API
- **格式**: GeoTIFF
- **费用**: 免费 (需要免费API key)
## 对比
| 方法 | 优点 | 缺点 |
|------|------|------|
| 自动下载 | ✓ 全自动<br>✓ 无需准备数据<br>✓ 快速便捷 | ✗ 需要API key<br>✗ 需要网络 |
| 预下载文件 | ✓ 离线使用<br>✓ 不依赖API | ✗ 需要手动下载<br>✗ 需要管理文件 |
## 示例
### 北京地区 (116-117°E, 39-40°N)
```bash
# 自动下载
python makedem.py -r 116/117/39/40 --dem-source srtm --opentopo-api-key YOUR_KEY
# 输出文件: SRTM_116_117_39_40.tif
```
### 使用SLC参数文件
```bash
# 自动确定区域范围
python makedem.py -s /path/to/slc.par --dem-source srtm --opentopo-api-key YOUR_KEY
```
## 常见问题
**Q: 为什么需要API key?**
A: OpenTopography要求API key来管理数据访问配额。免费API key配额足够大部分科研和教育用途。
**Q: 如何获取API key?**
A:
1. 访问 https://opentopography.org/myOpenTopo
2. 注册账户 (免费)
3. 在账户页面点击 "Request API Key"
4. API key会立即显示,可以直接使用
**Q: 免费API key有什么限制?**
A:
- SRTM GL3: 最大4,050,000 km² per request
- 对于大部分研究区域完全够用
- 如果需要更大范围,可以分块下载
**Q: SRTM vs Copernicus vs NASADEM?**
A:
- **Copernicus (推荐)**: 30m分辨率,全球覆盖,全自动下载
- **NASADEM**: 30m分辨率,NASA官方,60°S-60°N覆盖
- **SRTM**: 90m分辨率,历史数据,适合对比研究
**Q: 没有.hgt文件怎么办?**
A: 直接使用方法1自动下载,无需准备任何数据文件!
## 故障排除
### 错误: HTTP 401
**原因**: API key无效或已过期
**解决**:
- 检查API key是否正确
- 确认账户状态正常
- 如需要,重新生成API key
### 错误: HTTP 403
**原因**: 超出配额或访问限制
**解决**:
- 检查请求区域大小
- 分块下载大区域
- 确认API key配额
### 错误: 文件下载失败
**原因**: 网络问题
**解决**:
- 检查网络连接
- 重试命令
- 使用预下载方法
## Python版本兼容性
- **方法1 (自动下载)**: 支持所有Python版本
- **方法2 (使用.hgt文件)**:
- Python >= 3.12: 使用srtm库自动查询
- Python < 3.12: 使用GDAL手动处理
两种方法结果相同,只是处理方式不同。
## 相关资源
- OpenTopography: https://opentopography.org/
- API文档: https://portal.opentopography.org/apidocs/
- 获取API key: https://opentopography.org/myOpenTopo
- SRTM数据介绍: https://www2.jpl.nasa.gov/srtm/
---
**更新日期**: 2026-03-13
**功能版本**: v1.0
@@ -0,0 +1,128 @@
#! /usr/bin/env python
#'''
###################################################################################
# #
# Author: Yun-Meng Cao #
# Email : ymcmrs@gmail.com #
# Date : March, 2017 #
# #
# Transform lat and lon to SAR coordinates based on SLCPar and DEM #
# #
###################################################################################
#'''
import numpy as np
import os
import sys
import subprocess
import getopt
import time
import glob
def UseGamma(inFile, task, keyword):
if task == "read":
f = open(inFile, "r")
while 1:
line = f.readline()
if not line: break
if line.count(keyword) == 1:
strtemp = line.split(":")
value = strtemp[1].strip()
return value
print("Keyword " + keyword + " doesn't exist in " + inFile)
f.close()
def usage():
print('''
******************************************************************************************************
Transform lat and lon to SAR coordinates based on SLCPar and DEM
usage:
UTM2SARPIX.py latitude longitude SLCPar DEM
e.g. UTM2SARPIX.py 31.1 -108.2 /Yunmeng/2010.slc.par /Yunmeng/2010.dem
*******************************************************************************************************
''')
def main(argv):
if len(sys.argv)==5:
LAT = sys.argv[1]
LON = sys.argv[2]
PAR = sys.argv[3]
DEM = sys.argv[4]
else:
usage();sys.exit(1)
DEMpar = DEM + '.par'
DateFormat = UseGamma(DEMpar, 'read', 'data_format:')
nWidth = UseGamma(DEMpar, 'read', 'width:')
nLength = UseGamma(DEMpar, 'read', 'nlines:')
Corner_LAT = UseGamma(DEMpar, 'read', 'corner_lat:')
Corner_LON = UseGamma(DEMpar, 'read', 'corner_lon:')
Corner_LAT =Corner_LAT.split(' ')[0]
Corner_LON =Corner_LON.split(' ')[0]
post_Lat = UseGamma(DEMpar, 'read', 'post_lat:')
post_Lon = UseGamma(DEMpar, 'read', 'post_lon:')
post_Lat =post_Lat.split(' ')[0]
post_Lon =post_Lon.split(' ')[0]
if DateFormat =='INTEGER*2':
STR = '>i2'
else:
STR = '>f4'
TXT = 'SARCOORD'
DEMdate = np.fromfile(DEM,STR,int(nLength)*int(nWidth)).reshape(int(nLength),int(nWidth))
LAT = float(LAT); LON =float(LON)
nWidth=int(nWidth);nLength=int(nLength)
Corner_LAT = float(Corner_LAT); Corner_LON=float(Corner_LON)
post_Lat = float(post_Lat); post_Lon=float(post_Lon)
XX = int (( LAT - Corner_LAT ) / post_Lat) # latitude width range
YY = int (( LON - Corner_LON ) / post_Lon) # longitude nline azimuth
ELEV = DEMdate[XX][YY]
call_str = 'coord_to_sarpix ' + PAR + ' - - ' + str(LAT) + ' ' + str(LON) + ' ' + str(ELEV) + ' >' +TXT
os.system(call_str)
call_str = 'cat ' + TXT
os.system(call_str)
if __name__ == '__main__':
main(sys.argv[:])
@@ -0,0 +1,483 @@
############################################################
# Program is part of PyINT #
# Copyright 2019 Yunmeng Cao #
# Contact: ymcmrs@gmail.com #
############################################################
# This program is modified from MintPy/select_network.py
# Copyright: 2017-2019, Yunjun Zhang
# Contact: yzhang@rsmas.miami.edu
import os
import sys
import itertools
import h5py
import numpy as np
from scipy import sparse
from matplotlib import (colors,
dates as mdates,
pyplot as plt)
from matplotlib.tri import Triangulation
from mpl_toolkits.axes_grid1 import make_axes_locatable
##################################################################
def read_pairs_list(date12ListFile, dateList=[]):
"""Read Pairs List file like below:
070311-070426
070311-070611
...
"""
# Read date12 list file
date12List = sorted(list(np.loadtxt(date12ListFile, dtype=bytes).astype(str)))
# Get dateList from date12List
if not dateList:
dateList = []
for date12 in date12List:
dates = date12.split('-')
if not dates[0] in dateList:
dateList.append(dates[0])
if not dates[1] in dateList:
dateList.append(dates[1])
dateList.sort()
date6List = yymmdd(dateList)
# Get pair index
pairs_idx = []
for date12 in date12List:
dates = date12.split('-')
pair_idx = [date6List.index(dates[0]), date6List.index(dates[1])]
pairs_idx.append(pair_idx)
return pairs_idx
def get_date12_list(fname, dropIfgram=False):
"""Read Date12 info from input file: Pairs.list or multi-group hdf5 file
Inputs:
fname - string, path/name of input multi-group hdf5 file or text file
dropIfgram - bool, check the "DROP_IFGRAM" attribute or not for multi-group hdf5 file
Output:
date12_list - list of string in YYMMDD-YYMMDD format
Example:
date12List = get_date12_list('ifgramStack.h5')
date12List = get_date12_list('ifgramStack.h5', dropIfgram=True)
date12List = get_date12_list('Pairs.list')
"""
date12_list = []
ext = os.path.splitext(fname)[1].lower()
if ext == '.h5':
k = readfile.read_attribute(fname)['FILE_TYPE']
if k == 'ifgramStack':
date12_list = ifgramStack(fname).get_date12_list(dropIfgram=dropIfgram)
else:
return None
else:
txtContent = np.loadtxt(fname, dtype=bytes).astype(str)
if len(txtContent.shape) == 1:
txtContent = txtContent.reshape(-1, 1)
date12_list = [i for i in txtContent[:, 0]]
date12_list = sorted(date12_list)
return date12_list
def igram_perp_baseline_list(fname):
"""Get perpendicular baseline list from input multi_group hdf5 file"""
print(('read perp baseline info from '+fname))
k = readfile.read_attribute(fname)['FILE_TYPE']
h5 = h5py.File(fname, 'r')
epochList = sorted(h5[k].keys())
p_baseline_list = []
for epoch in epochList:
p_baseline = (float(h5[k][epoch].attrs['P_BASELINE_BOTTOM_HDR']) +
float(h5[k][epoch].attrs['P_BASELINE_TOP_HDR']))/2
p_baseline_list.append(p_baseline)
h5.close()
return p_baseline_list
def select_pairs_sbas(date_list, date12_format='YYMMDD-YYMMDD'):
"""Select All Possible Pairs/Interferograms
Input : date_list - list of date in YYMMDD/YYYYMMDD format
Output: date12_list - list date12 in YYMMDD-YYMMDD format
Reference:
Berardino, P., G. Fornaro, R. Lanari, and E. Sansosti (2002), A new algorithm for surface deformation monitoring
based on small baseline differential SAR interferograms, IEEE TGRS, 40(11), 2375-2383.
"""
date8_list = sorted(yyyymmdd(date_list))
date6_list = yymmdd(date8_list)
date12_list = list(itertools.combinations(date6_list, 2))
date12_list = [date12[0]+'-'+date12[1] for date12 in date12_list]
if date12_format == 'YYYYMMDD_YYYYMMDD':
date12_list = yyyymmdd_date12(date12_list)
return date12_list
def select_pairs_sequential(date_list, num_connection=2, date12_format='YYMMDD-YYMMDD'):
"""Select Pairs in a Sequential way:
For each acquisition, find its num_connection nearest acquisitions in the past time.
Inputs:
date_list : list of date in YYMMDD/YYYYMMDD format
Reference:
Fattahi, H., and F. Amelung (2013), DEM Error Correction in InSAR Time Series, IEEE TGRS, 51(7), 4249-4259.
"""
date8_list = sorted(yyyymmdd(date_list))
date6_list = yymmdd(date8_list)
date_idx_list = list(range(len(date6_list)))
# Get pairs index list
date12_idx_list = []
for date_idx in date_idx_list:
for i in range(num_connection):
if date_idx-i-1 >= 0:
date12_idx_list.append([date_idx-i-1, date_idx])
date12_idx_list = [sorted(idx) for idx in sorted(date12_idx_list)]
# Convert index into date12
date12_list = [date6_list[idx[0]]+'-'+date6_list[idx[1]]
for idx in date12_idx_list]
if date12_format == 'YYYYMMDD_YYYYMMDD':
date12_list = yyyymmdd_date12(date12_list)
return date12_list
def select_pairs_hierarchical(date_list, pbase_list, temp_perp_list, date12_format='YYMMDD-YYMMDD'):
"""Select Pairs in a hierarchical way using list of temporal and perpendicular baseline thresholds
For each temporal/perpendicular combination, select all possible pairs; and then merge all combination results
together for the final output (Zhao, 2015).
Inputs:
date_list : list of date in YYMMDD/YYYYMMDD format
pbase_list : list of float, perpendicular spatial baseline
temp_perp_list : list of list of 2 floats, for list of temporal/perp baseline, e.g.
[[32.0, 800.0], [48.0, 600.0], [64.0, 200.0]]
Examples:
pairs = select_pairs_hierarchical(date_list, pbase_list, [[32.0, 800.0], [48.0, 600.0], [64.0, 200.0]])
Reference:
Zhao, W., (2015), Small deformation detected from InSAR time-series and their applications in geophysics, Doctoral
dissertation, Univ. of Miami, Section 6.3.
"""
# Get all date12
date12_list_all = select_pairs_all(date_list)
# Loop of Threshold
print('List of temporal and perpendicular spatial baseline thresholds:')
print(temp_perp_list)
date12_list = []
for temp_perp in temp_perp_list:
tbase_max = temp_perp[0]
pbase_max = temp_perp[1]
date12_list_tmp = threshold_temporal_baseline(date12_list_all,
tbase_max,
keep_seasonal=False)
date12_list_tmp = threshold_perp_baseline(date12_list_tmp,
date_list,
pbase_list,
pbase_max)
date12_list += date12_list_tmp
date12_list = sorted(list(set(date12_list)))
if date12_format == 'YYYYMMDD_YYYYMMDD':
date12_list = yyyymmdd_date12(date12_list)
return date12_list
def select_pairs_delaunay(date_list, tbase_list, pbase_list, norm=True, date12_format='YYMMDD-YYMMDD'):
"""Select Pairs using Delaunay Triangulation based on temporal/perpendicular baselines
Inputs:
date_list : list of date in YYMMDD/YYYYMMDD format
pbase_list : list of float, perpendicular spatial baseline
norm : normalize temporal baseline to perpendicular baseline
Key points
1. Define a ratio between perpendicular and temporal baseline axis units (Pepe and Lanari, 2006, TGRS).
2. Pairs with too large perpendicular / temporal baseline or Doppler centroid difference should be removed
after this, using a threshold, to avoid strong decorrelations (Zebker and Villasenor, 1992, TGRS).
Reference:
Pepe, A., and R. Lanari (2006), On the extension of the minimum cost flow algorithm for phase unwrapping
of multitemporal differential SAR interferograms, IEEE TGRS, 44(9), 2374-2383.
Zebker, H. A., and J. Villasenor (1992), Decorrelation in interferometric radar echoes, IEEE TGRS, 30(5), 950-959.
"""
# Get temporal baseline in days
date6_list = yymmdd(date_list)
date8_list = yyyymmdd(date_list)
#tbase_list = date_list2tbase(date8_list)[0]
# Normalization (Pepe and Lanari, 2006, TGRS)
if norm:
temp2perp_scale = (max(pbase_list)-min(pbase_list)) / (max(tbase_list)-min(tbase_list))
tbase_list = [tbase*temp2perp_scale for tbase in tbase_list]
# Generate Delaunay Triangulation
date12_idx_list = Triangulation(tbase_list, pbase_list).edges.tolist()
date12_idx_list = [sorted(idx) for idx in sorted(date12_idx_list)]
# Convert index into date12
date12_list = [date6_list[idx[0]]+'-'+date6_list[idx[1]]
for idx in date12_idx_list]
if date12_format == 'YYYYMMDD_YYYYMMDD':
date12_list = yyyymmdd_date12(date12_list)
return date12_list
def select_pairs_mst(date_list, pbase_list, date12_format='YYMMDD-YYMMDD'):
"""Select Pairs using Minimum Spanning Tree technique
Connection Cost is calculated using the baseline distance in perp and scaled temporal baseline (Pepe and Lanari,
2006, TGRS) plane.
Inputs:
date_list : list of date in YYMMDD/YYYYMMDD format
pbase_list : list of float, perpendicular spatial baseline
References:
Pepe, A., and R. Lanari (2006), On the extension of the minimum cost flow algorithm for phase unwrapping
of multitemporal differential SAR interferograms, IEEE TGRS, 44(9), 2374-2383.
Perissin D., Wang T. (2012), Repeat-pass SAR interferometry with partially coherent targets. IEEE TGRS. 271-280
"""
# Get temporal baseline in days
date6_list = yymmdd(date_list)
date8_list = yyyymmdd(date_list)
tbase_list = date_list2tbase(date8_list)[0]
# Normalization (Pepe and Lanari, 2006, TGRS)
temp2perp_scale = (max(pbase_list)-min(pbase_list)) / (max(tbase_list)-min(tbase_list))
tbase_list = [tbase*temp2perp_scale for tbase in tbase_list]
# Get weight matrix
ttMat1, ttMat2 = np.meshgrid(np.array(tbase_list), np.array(tbase_list))
ppMat1, ppMat2 = np.meshgrid(np.array(pbase_list), np.array(pbase_list))
ttMat = np.abs(ttMat1 - ttMat2) # temporal distance matrix
ppMat = np.abs(ppMat1 - ppMat2) # spatial distance matrix
# 2D distance matrix in temp/perp domain
weightMat = np.sqrt(np.square(ttMat) + np.square(ppMat))
weightMat = sparse.csr_matrix(weightMat) # compress sparse row matrix
# MST path based on weight matrix
mstMat = sparse.csgraph.minimum_spanning_tree(weightMat)
# Convert MST index matrix into date12 list
[s_idx_list, m_idx_list] = [date_idx_array.tolist()
for date_idx_array in sparse.find(mstMat)[0:2]]
date12_list = []
for i in range(len(m_idx_list)):
idx = sorted([m_idx_list[i], s_idx_list[i]])
date12 = date6_list[idx[0]]+'-'+date6_list[idx[1]]
date12_list.append(date12)
if date12_format == 'YYYYMMDD_YYYYMMDD':
date12_list = yyyymmdd_date12(date12_list)
return date12_list
def select_pairs_star(date_list, m_date=None, pbase_list=[], date12_format='YYMMDD-YYMMDD'):
"""Select Star-like network/interferograms/pairs, it's a single master network, similar to PS approach.
Usage:
m_date : master date, choose it based on the following cretiria:
1) near the center in temporal and spatial baseline
2) prefer winter season than summer season for less temporal decorrelation
Reference:
Ferretti, A., C. Prati, and F. Rocca (2001), Permanent scatterers in SAR interferometry, IEEE TGRS, 39(1), 8-20.
"""
date8_list = sorted(yyyymmdd(date_list))
date6_list = yymmdd(date8_list)
# Select master date if not existed
if not m_date:
m_date = select_master_date(date8_list, pbase_list)
print(('auto select master date: '+m_date))
# Check input master date
m_date8 = yyyymmdd(m_date)
if m_date8 not in date8_list:
print('Input master date is not existed in date list!')
print(('Input master date: '+str(m_date8)))
print(('Input date list: '+str(date8_list)))
m_date8 = None
# Generate star/ps network
m_idx = date8_list.index(m_date8)
date12_idx_list = [sorted([m_idx, s_idx]) for s_idx in range(len(date8_list))
if s_idx is not m_idx]
date12_list = [date6_list[idx[0]]+'-'+date6_list[idx[1]]
for idx in date12_idx_list]
if date12_format == 'YYYYMMDD_YYYYMMDD':
date12_list = yyyymmdd_date12(date12_list)
return date12_list
def select_master_date(date_list, pbase_list=[]):
"""Select super master date based on input temporal and/or perpendicular baseline info.
Return master date in YYYYMMDD format.
"""
date8_list = yyyymmdd(date_list)
if not pbase_list:
# Choose date in the middle
m_date8 = date8_list[int(len(date8_list)/2)]
else:
# Get temporal baseline list
tbase_list = date_list2tbase(date8_list)[0]
# Normalization (Pepe and Lanari, 2006, TGRS)
temp2perp_scale = (max(pbase_list)-min(pbase_list)) / (max(tbase_list)-min(tbase_list))
tbase_list = [tbase*temp2perp_scale for tbase in tbase_list]
# Get distance matrix
ttMat1, ttMat2 = np.meshgrid(np.array(tbase_list),
np.array(tbase_list))
ppMat1, ppMat2 = np.meshgrid(np.array(pbase_list),
np.array(pbase_list))
ttMat = np.abs(ttMat1 - ttMat2) # temporal distance matrix
ppMat = np.abs(ppMat1 - ppMat2) # spatial distance matrix
# 2D distance matrix in temp/perp domain
disMat = np.sqrt(np.square(ttMat) + np.square(ppMat))
# Choose date minimize the total distance of temp/perp baseline
disMean = np.mean(disMat, 0)
m_idx = np.argmin(disMean)
m_date8 = date8_list[m_idx]
return m_date8
def select_master_interferogram(date12_list, date_list, pbase_list, m_date=None):
"""Select reference interferogram based on input temp/perp baseline info
If master_date is specified, select its closest slave_date, which is newer than master_date;
otherwise, choose the closest pair among all pairs as master interferogram.
Example:
master_date12 = pnet.select_master_ifgram(date12_list, date_list, pbase_list)
'080211-080326' = pnet.select_master_ifgram(date12_list, date_list, pbase_list, m_date='080211')
"""
pbase_array = np.array(pbase_list, dtype='float64')
# Get temporal baseline
date8_list = yyyymmdd(date_list)
date6_list = yymmdd(date8_list)
tbase_array = np.array(date_list2tbase(date8_list)[0], dtype='float64')
# Normalization (Pepe and Lanari, 2006, TGRS)
temp2perp_scale = (max(pbase_array)-min(pbase_array)) / (max(tbase_array)-min(tbase_array))
tbase_array *= temp2perp_scale
# Calculate sqrt of temp/perp baseline for input pairs
idx1 = np.array([date6_list.index(date12.split('-')[0]) for date12 in date12_list])
idx2 = np.array([date6_list.index(date12.split('-')[1]) for date12 in date12_list])
base_distance = np.sqrt((tbase_array[idx2] - tbase_array[idx1])**2 +
(pbase_array[idx2] - pbase_array[idx1])**2)
# Get master interferogram index
if not m_date:
# Choose pair with shortest temp/perp baseline
m_date12_idx = np.argmin(base_distance)
else:
m_date = yymmdd(m_date)
# Choose pair contains m_date with shortest temp/perp baseline
m_date12_idx_array = np.array([date12_list.index(date12) for date12 in date12_list
if m_date+'-' in date12])
min_base_distance = np.min(base_distance[m_date12_idx_array])
m_date12_idx = np.where(base_distance == min_base_distance)[0][0]
m_date12 = date12_list[m_date12_idx]
return m_date12
##########################################################
def datenum2datetime(datenum):
"""Convert Matlab datenum into Python datetime.
Parameters: datenum : Date in datenum format, i.e. 731763.5
Returns: datetime: Date in datetime.datetime format, datetime.datetime(2003, 7, 1, 12, 0)
"""
return dt.fromordinal(int(datenum)) \
+ timedelta(days=datenum % 1) \
- timedelta(days=366)
def decimal_year2datetime(years):
"""read date in 2002.40657084 to datetime format
Parameters: years : (list of) float or str for years
Returns: years_dt : (list of) datetime.datetime objects
"""
def decimal_year2datetime1(x):
x = float(x)
year = np.floor(x).astype(int)
yday = np.floor((x - year) * 365.25).astype(int) + 1
x2 = '{:d}-{:d}'.format(year, yday)
try:
xt = dt(*time.strptime(x2, "%Y-%j")[0:5])
except:
raise ValueError('wrong format: ',x)
return xt
if isinstance(years, (float, str)):
years_dt = decimal_year2datetime1(years)
elif isinstance(years, list):
years_dt = []
for year in years:
years_dt.append(decimal_year2datetime1(year))
else:
raise ValueError('unrecognized input format: {}. Only float/str/list are supported.'.format(type(years)))
return years_dt
def yyyymmdd2years(dates):
if isinstance(dates, str):
d = dt(*time.strptime(dates, "%Y%m%d")[0:5])
yy = float(d.year)+float(d.timetuple().tm_yday-1)/365.25
elif isinstance(dates, list):
yy = []
for date in dates:
d = dt(*time.strptime(date, "%Y%m%d")[0:5])
yy.append(float(d.year)+float(d.timetuple().tm_yday-1)/365.25)
else:
raise ValueError('Unrecognized date format. Only string and list supported.')
return yy
def yymmdd2yyyymmdd(date):
if date[0] == '9':
date = '19'+date
else:
date = '20'+date
return date
def yyyymmdd(dates):
if isinstance(dates, str):
if len(dates) == 6:
datesOut = yymmdd2yyyymmdd(dates)
else:
datesOut = dates
elif isinstance(dates, list):
datesOut = []
for date in dates:
if len(date) == 6:
date = yymmdd2yyyymmdd(date)
datesOut.append(date)
else:
# print 'Un-recognized date input!'
return None
return datesOut
def yymmdd(dates):
if isinstance(dates, str):
if len(dates) == 8:
datesOut = dates[2:8]
else:
datesOut = dates
elif isinstance(dates, list):
datesOut = []
for date in dates:
if len(date) == 8:
date = date[2:8]
datesOut.append(date)
else:
# print 'Un-recognized date input!'
return None
return datesOut
def yyyymmdd_date12(date12_list):
"""Convert date12 into YYYYMMDD_YYYYMMDD format"""
m_dates = yyyymmdd([i.replace('-', '_').split('_')[0] for i in date12_list])
s_dates = yyyymmdd([i.replace('-', '_').split('_')[1] for i in date12_list])
date12_list = ['{}-{}'.format(m, s) for m, s in zip(m_dates, s_dates)]
return date12_list
def yymmdd_date12(date12_list):
"""Convert date12 into YYMMDD-YYMMDD format"""
m_dates = yymmdd([i.replace('-', '_').split('_')[0] for i in date12_list])
s_dates = yymmdd([i.replace('-', '_').split('_')[1] for i in date12_list])
date12_list = ['{}-{}'.format(m, s) for m, s in zip(m_dates, s_dates)]
return date12_list
@@ -0,0 +1,93 @@
import os
import subprocess
import sys
TRUE_VALUES = {"1", "true", "yes", "on"}
def _read_bool_env(name, default=False):
value = os.getenv(name)
if value is None:
return default
return str(value).strip().lower() in TRUE_VALUES
def apply_precise_orbit(date_text, slc_par_paths, work_dir=None, operation_tag="raw2slc"):
helper_path = str(os.getenv("PYINT_LT1_PRECISE_ORBIT_HELPER") or "").strip()
manifest_json = str(os.getenv("PYINT_LT1_PRECISE_ORBIT_MANIFEST") or "").strip()
enabled = _read_bool_env("PYINT_LT1_PRECISE_ORBIT_ENABLED", False)
strict = _read_bool_env("PYINT_LT1_PRECISE_ORBIT_STRICT", True)
result = {
"enabled": enabled,
"helper_path": helper_path,
"manifest_json": manifest_json,
"summary_json": "",
"returncode": 0,
"stdout": "",
"stderr": "",
"command": [],
"applied_files": [],
"status": "disabled",
}
if not enabled:
return result
if not helper_path or not os.path.isfile(helper_path):
message = "PYINT_LT1_PRECISE_ORBIT_HELPER is missing or does not exist."
result.update({"status": "missing_helper", "stderr": message})
if strict:
raise RuntimeError(message)
return result
if not manifest_json:
message = "PYINT_LT1_PRECISE_ORBIT_MANIFEST is empty."
result.update({"status": "missing_manifest", "stderr": message})
if strict:
raise RuntimeError(message)
return result
files = []
for path in slc_par_paths or []:
text = str(path or "").strip()
if text and os.path.isfile(text):
files.append(text)
result["applied_files"] = files
if not files:
result["status"] = "skipped"
return result
summary_json = os.path.join(str(work_dir or os.getcwd()), "orbit_bridge_summary.json")
command = [
sys.executable,
helper_path,
"--date",
str(date_text or "").strip(),
"--manifest-json",
manifest_json,
"--summary-json",
summary_json,
"--operation-tag",
str(operation_tag or "raw2slc"),
]
for path in files:
command.extend(["--slc-par", path])
result["summary_json"] = summary_json
result["command"] = command
proc = subprocess.run(
command,
text=True,
capture_output=True,
check=False,
)
result.update(
{
"returncode": int(proc.returncode),
"stdout": proc.stdout or "",
"stderr": proc.stderr or "",
"status": "applied" if proc.returncode == 0 else "failed",
}
)
if proc.returncode != 0 and strict:
raise RuntimeError(result["stderr"] or result["stdout"] or "Precise orbit bridge failed.")
return result
@@ -0,0 +1,689 @@
############################################################
# Program is part of PyINT V2.1 #
# Copyright 2017-2019 Yunmeng Cao #
# Contact: ymcmrs@gmail.com #
############################################################
#from datetime import datetime
import datetime
import urllib.request
import os
import numpy as np
import random
import h5py
from pathlib import Path
import linecache
import time
import glob
from tqdm import tqdm
from concurrent.futures import ProcessPoolExecutor, as_completed
# 无条件清理 OMP_PLACES / OMP_PROC_BIND,避免 libgomp 报错
for _k in ('OMP_PLACES', 'OMP_PROC_BIND'):
os.environ.pop(_k, None)
####################### update template #############################
def update_template(template_file):
templateDict = {}
######### download using SSARA ######
#templateDict['sensor'] = 'sentinel-1'
#templateDict['track'] = '14'
#templateDict['frame'] = '75'
templateDict['start_time'] = '1989-01-01'
templateDict['end_time'] = '2189-01-01'
######### download using ASF API ######
templateDict['asf_username'] = '' # ASF username (can be read from ~/.netrc)
templateDict['asf_password'] = '' # ASF password (can be read from ~/.netrc)
templateDict['bbox'] = '' # bounding box: min_lon,min_lat,max_lon,max_lat
templateDict['shapefile'] = '' # shapefile path for spatial filtering
templateDict['relative_orbit'] = '' # relative orbit number (optional)
templateDict['frame'] = '' # frame number (optional)
templateDict['flight_direction'] = 'a' # flight direction: a=ascending, d=descending, all
templateDict['acquisition_mode'] = 'IW' # acquisition mode: IW, EW, SM, all
####### basic parameters for interferometry ######
templateDict['start_swath'] = '1'
templateDict['end_swath'] = '3'
templateDict['start_burst'] = '1'
templateDict['end_burst'] = '20'
templateDict['dem_lat_ovr'] = '0.5' # get 30m resolution of lookup table, 0.5 to 60m, 2 to 15m
templateDict['dem_lon_ovr'] = '0.5' # get 30m resolution of lookup table
templateDict['dem_num_workers'] = '4' # number of parallel workers for DEM download
templateDict['dem_source'] = 'copernicus' # DEM data source: copernicus or nasadem
templateDict['Igram_Spsflg'] = '1' # Range spectral filtering
templateDict['Igram_Azfflg'] = '1' # Azimuth common band filtering
templateDict['rwin4cor'] = '256' # range window length for coregistration
templateDict['azwin4cor'] = '256' # azimuth window length for coregistration
templateDict['rsample4cor'] = '32' # range samples used for fitting the coregistration parameters
templateDict['azsample4cor'] = '32' # azimuth samples used for fitting the coregistration parameters
templateDict['thresh4cor'] = '0.15' # 2016 GAMMA or higher version, for 2015 GAMMA or lower version should be SNR
templateDict['coreCoarse'] = 'both' # initial coregistration method, [options: orbit, ampcor, both]
templateDict['coreMethod'] = 'DEM' # coregistration method [option: DEM, init] DEM means with DEM assistant
templateDict['Igram_Cor_rwin'] = '5' # used for cc_wave
templateDict['Igram_Cor_awin'] = '5' # used for cc_wave
templateDict['Igram_Cor_Win'] = '5' # used for adf
templateDict['adf_alpha'] = '0.4' # used for adf
######## sim phase ##################
templateDict['Igram_Flag_TDM'] = 'N'
templateDict['Simphase_rpos'] = '-'
templateDict['Simphase_azpos'] = '-'
templateDict['Simphase_rwin'] = '256'
templateDict['Simphase_azwin'] = '256'
templateDict['Simphase_thresh'] = '-'
#### unwrap phase ###########
templateDict['auto_unw'] = '1' # auto reference-point selection
templateDict['make_mask'] = '1' # coherence-mask switch for unwrap
templateDict['init_flag'] = '1' # set reference-point phase to 0.0
templateDict['r_refer'] = '-' # range reference pixel for manual unwrap
templateDict['a_refer'] = '-' # azimuth reference pixel for manual unwrap
templateDict['mcf_triangular'] = '0' # triangular type of mcf [0: regular; 1: delaunay;]
templateDict['unwrap_patr'] = '4'
templateDict['unwrap_pataz'] = '4'
templateDict['unwrapThreshold'] = '0.1' # minimum coherence used for unwrap
#### geocode #########
templateDict['geo_interp'] = '0' # [0: nearest; 1: bicubic spline]
templateDict['geocode_products'] = 'hyp3,licsbas' # 产品类型: hyp3,licsbas,pot (逗号分隔多选)
############## interferometry ################
templateDict['int_flag'] = '1' # 1 means do interferometry
templateDict['diff_flag'] = '1' # differential process, i.e., remove DEM phase
templateDict['unw_flag'] = '1' # unwrap process
templateDict['geo_flag'] = '0' # geocode process
############## select network #############
templateDict['endDate'] = '21000101'
templateDict['startDate'] = '19000101'
templateDict['network_method'] = 'sbas' # sbas, sequential, delaunay, stars
templateDict['conNumb'] = '2' # connect number for sequential
templateDict['max_tb'] = '50000'
templateDict['max_sb'] = '50000'
############## time-series ################
templateDict['download_data'] = '0' # if 1, track, frame, or time informations should be provided
templateDict['down_parallel'] = '1' # multi-processor number used for downloading
templateDict['raw2slc_all'] = '0' # i.e., download 2 slc
templateDict['raw2slc_all_parallel'] = '1' # multi-processor number used
templateDict['extract_burst_all'] = '0' # for TOPS SLC only
templateDict['extract_all_parallel'] = '1' # multi-processor number used
templateDict['coreg_all'] = '1'
templateDict['coreg_all_parallel'] = '1' # multi-processor number used [4 or 8]
templateDict['select_pairs'] = '1'
templateDict['diff_all'] = '1'
templateDict['diff_all_parallel'] = '1' # multi-processor number used [4 or 8]
templateDict['unwrap_all'] = '1'
templateDict['unwrap_all_parallel'] = '1' # multi-processor number used [8 or 10]
templateDict['atmcor_all'] = '0' # if 1, run atmospheric correction
templateDict['atmcor_all_parallel'] = '1' # multi-processor number used
templateDict['geocode_all'] = '0'
templateDict['geocode_all_parallel'] = '1' # multi-processor number used
templateDict['gamma2licsbas_all'] = '0' # legacy conversion stage switch
templateDict['gamma2licsbas_all_parallel'] = '1'
templateDict['hyp3format_all'] = '0' # legacy conversion stage switch
templateDict['hyp3format_all_parallel'] = '1'
############## GACOS atmospheric correction #############
templateDict['gacos_correction'] = '0' # if 1, apply GACOS atmospheric correction
templateDict['gacos_all_parallel'] = '1' # multi-processor number used for GACOS correction
templateDict['gacos_dir'] = '' # directory for GACOS ZTD files (default: projectName/GACOS)
templateDict['gacos_email'] = '' # email for GACOS auto-download
templateDict['gacos_email_user'] = '' # IMAP username
templateDict['gacos_email_pass'] = '' # IMAP authorization code
templateDict['gacos_email_host'] = 'imap.163.com' # IMAP server host
templateDict['gacos_email_port'] = '993' # IMAP server port
templateDict['gacos_email_ssl'] = '1' # Use SSL
templateDict['gacos_check_interval'] = '60' # Email check interval (seconds)
############## Pixel Offset Tracking (POT) #############
templateDict['pot_all'] = '0' # if 1, run offset tracking
templateDict['pot_all_parallel'] = '1' # multi-processor number used
templateDict['pot_rstep'] = '50' # range step in SLC pixels
templateDict['pot_azstep'] = '10' # azimuth step in SLC pixels
templateDict['pot_rwin'] = '256' # range window size (Round 1)
templateDict['pot_azwin'] = '128' # azimuth window size (Round 1)
templateDict['pot_rwin2'] = '128' # range window size (Round 2)
templateDict['pot_azwin2'] = '64' # azimuth window size (Round 2)
templateDict['pot_ovr'] = '1' # SLC oversampling factor (1=no deramp needed)
templateDict['pot_snr_thresh'] = '0.01' # SNR threshold for offset_pwr_tracking
templateDict['pot_ccp_thresh'] = '0.05' # cross-correlation threshold for masking
templateDict['pot_roff_min'] = '-50' # min range offset (pixels) for masking
templateDict['pot_roff_max'] = '50' # max range offset (pixels) for masking
templateDict['pot_azoff_min'] = '-20' # min azimuth offset (pixels) for masking
templateDict['pot_azoff_max'] = '20' # max azimuth offset (pixels) for masking
templateDict['pot_drange_thresh'] = '2.0' # deviation threshold range (pixels)
templateDict['pot_dazimuth_thresh'] = '1.0' # deviation threshold azimuth (pixels)
templateDict['pot_median_win'] = '7' # median filter window size
templateDict['pot_median_nmin'] = '15' # min valid samples for median filter
templateDict['pot_two_rounds'] = '1' # 1=two-round estimation, 0=single round
templateDict['pot_geocode'] = '1' # 1=geocode displacement results
templateDict['pot_disp_max'] = '100' # max displacement for BMP display (meters)
templateDict['load_data'] = '0' # loading data for mintpy processing
templateDict0 = read_template(template_file, delimiter='=')
for key, value in templateDict0.items():
templateDict[key] = str(value)
return templateDict
####################### time-related function ################
def is_number(s):
try:
int(s)
return True
except ValueError:
return False
def print_process_time(start, end):
hours, rem = divmod(end-start, 3600)
minutes, seconds = divmod(rem, 60)
print("Total process time: "+"{:0>2}:{:0>2}:{:05.2f}".format(int(hours),int(minutes),seconds))
return
def date_add1d(date0):
format_str = '%Y%m%d' # The format
date_obj = datetime.datetime.strptime(date0,format_str)
date1 = (date_obj + datetime.timedelta(days=1)).date().strftime('%Y%m%d')
return date1
def date_minus1d(date0):
format_str = '%Y%m%d' # The format
date_obj = datetime.datetime.strptime(date0,format_str)
date1 = (date_obj - datetime.timedelta(days=1)).date().strftime('%Y%m%d')
return date1
def generate_random_name(sufix):
nowTime = datetime.datetime.now().strftime("%Y%m%d%H%M%S") #generate the present time
randomNum = random.randint(0,100)
randomNum1 = random.randint(0,100)
Nm = nowTime + str(randomNum)+ str(randomNum1) + sufix
return Nm
def yyyymmdd2yyyyddd(date):
dt = datetime.datetime.strptime(date, "%Y%m%d") # get datetime object
day_of_year = (dt - datetime.datetime(dt.year, 1, 1)) # Jan the 1st is day 1
doy = day_of_year.days + 1
year = dt.year
doy = str(doy)
if len(doy) ==1:
doy = '00' + doy
elif len(doy) ==2:
doy ='0'+ doy
year = str(year)
return year, doy
def get_txt_lines(txt):
count=0
myfile=open(txt,"r")
for line in myfile:
count=count+1
return count
def read_txt2list(txt):
A = np.loadtxt(txt,dtype=str)
if np.array(A).size ==1:
A = [A]
elif isinstance(A[0],bytes):
A = A.astype(str)
A = list(A)
return A
def read_txt2array(txt):
A = np.loadtxt(txt,dtype=str)
if np.array(A).size ==1:
A = [A]
elif isinstance(A[0],bytes):
A = A.astype(str)
#A = list(A)
return A
def get_sardata_swath(start_swath,end_swath):
k_swath = '0'
if (start_swath == '1') and (end_swath == '1'):
k_swath = '1'
elif (start_swath == '2') and (end_swath == '2'):
k_swath = '2'
elif (start_swath == '3') and (end_swath == '3'):
k_swath = '3'
elif (start_swath == '1') and (end_swath == '2'):
k_swath = '4'
elif (start_swath == '2') and (end_swath == '3'):
k_swath = '5'
elif (start_swath == '2') and (end_swath == '3'):
k_swath = '-'
return k_swath
def get_filelist_filesize(url0):
ttt = generate_random_name('.txt')
call_str = 'curl -s ' + url0 + ' > ' + ttt
os.system(call_str)
A = read_txt2array(ttt)
A_size = A[:,4]
A_size = A_size.astype(int)
A_size = A_size/1024/1024 #bytes to Mb
A_name = A[:,8]
if os.path.isfile(ttt):
os.remove(ttt)
return A_name, A_size
def yyyymmdd(date0):
if len(date0) ==6:
if float(date0[0:2]) > 90:
date1 = '19' + date0
else:
date1 = '20' + date0
elif len(date0) ==8:
date1 = date0
else:
print('The input date is invalid!!')
date1 = ''
return date1
def yymmdd(date0):
if len(date0) ==6:
date1 = date0
elif len(date0) ==8:
date1 = date0[2:8]
else:
print('The input date is invalid!!')
date1 = ''
return date1
def parallel_process(array, function, n_jobs=16, use_kwargs=False):
"""
A parallel version of the map function with a progress bar.
Args:
array (array-like): An array to iterate over.
function (function): A python function to apply to the elements of array
n_jobs (int, default=16): The number of cores to use
use_kwargs (boolean, default=False): Whether to consider the elements of array as dictionaries of
keyword arguments to function
Returns:
[function(array[0]), function(array[1]), ...]
"""
#We run the first few iterations serially to catch bugs
#If we set n_jobs to 1, just run a list comprehension. This is useful for benchmarking and debugging.
if n_jobs==1:
return [function(**a) if use_kwargs else function(a) for a in tqdm(array[:])]
#Assemble the workers
with ProcessPoolExecutor(max_workers=n_jobs) as pool:
#Pass the elements of array into function
if use_kwargs:
futures = [pool.submit(function, **a) for a in array[:]]
else:
futures = [pool.submit(function, a) for a in array[:]]
kwargs = {
'total': len(futures),
'unit': 'it',
'unit_scale': True,
'leave': True
}
#Print out the progress as tasks complete
for f in tqdm(as_completed(futures), **kwargs):
pass
out = []
#Get the results from the futures.
for i, future in tqdm(enumerate(futures)):
try:
out.append(future.result())
except Exception as e:
out.append(e)
return out
def sort_unique_list(numb_list):
list_out = sorted(set(numb_list))
return list_out
############################# download data ###################################
def StrNum(S):
S = str(S)
if len(S)==1:
S='0' +S
return S
def download_s1_orbit(date,save_path,satellite='A'):
DATE = date
if len(DATE)==6:
DATE = '20' + DATE
ST = satellite
YEAR = int(DATE[0:4])
MON = int(DATE[4:6])
DAY = int(DATE[6:8])
MON_DAY = [31,28,31,30,31,30,31,31,30,31,30,31]
if YEAR%4==0:
MON_DAY[1]=29
if MON ==1 and DAY ==1:
DAY0 = 31
MON0 = 12
YEAR0 =YEAR -1
elif MON!=1 and DAY ==1:
DAY0 = MON_DAY[MON-2]
MON0 = MON-1
YEAR0 = YEAR
else:
DAY0 = DAY -1
MON0 = MON
YEAR0 = YEAR
MONDAY0 = MON_DAY[MON0-1]
TT = [1,4,7,10,13,16,19,22,25,28,MONDAY0]
T0 = []
for k in range(len(TT)):
T0.append(TT[k])
TT[k] = TT[k]-DAY0
for k in range(len(TT)):
if k == len(TT)-1:
if TT[k]==0:
ff = k-1
else:
if TT[k]<=0 and TT[k+1]>0:
ff = k
DAY1 = T0[ff]
DAY2 = T0[ff+1]
S1 = StrNum(YEAR0) + '-' + StrNum(MON0)
S2 = StrNum(YEAR0) + '-' + StrNum(MON0) + '-' + StrNum(DAY1)
S3 = StrNum(YEAR0) + '-' + StrNum(MON0) + '-' + StrNum(DAY2)
S4 = StrNum(YEAR0) + '-' + StrNum(MON0) + '-' + StrNum(DAY0)
#SS = 'https://qc.sentinel1.eo.esa.int/aux_poeorb/?mission=S1' + ST + '&validity_start_time=' + StrNum(YEAR0) + '&validity_start_time=' + S1 + '&validity_start_time=' + S2 + '..' + S3 + '&validity_start_time=' + S4
SS = 'https://qc.sentinel1.eo.esa.int/aux_poeorb/?validity_start=' + StrNum(YEAR0) + '&validity_start=' + S1 + '&validity_start=' + S2 + '..' + S3 + '&validity_start=' +S4 + '&sentinel1__mission=S1'+ST+ '&sentinel1_mission=S1'+ST+ '&sentinel1_mission=S1'+ST+ '&sentinel1_mission=S1'+ST
tt ='tt_orb_' + date
tt0 ='tt0_orb_' + date
tt00 ='tt00_orb_' + date
tt000 ='tt000_orb_' + date
SS = "'" + SS + "'"
#print(SS)
call_str = 'curl -s -l ' + SS + ' > ' + tt
os.system(call_str)
call_str = "grep 'EOF' -C 0 " + tt + " >" + tt0
os.system(call_str)
call_str="awk -F'href=' '{print $2}' " + tt0 +' >' + tt00
os.system(call_str)
call_str= "awk -F'>' '{print $1}' " + tt00 + '> ' + tt000
os.system(call_str)
SS=linecache.getline(tt000, 1)
SS = SS.split('"')[1]
filename = os.path.basename(SS)
if not os.path.isfile(filename):
call_str = 'wget -q --no-check-certificate ' + SS + ' -O ' + save_path + '/' +filename
os.system(call_str)
call_str = "downlaod the precise Orbit of" + date
print(call_str)
filename = os.path.basename(SS)
os.remove(tt)
os.remove(tt0)
os.remove(tt00)
os.remove(tt000)
return filename
############################# write & read #####################################
def copy_file(file0,file1):
call_str = 'cp ' + file0 + ' ' + file1
os.system(call_str)
return
def get_project_slcList(projectName):
scratchDir = os.getenv('SCRATCHDIR')
slcDir = scratchDir + '/' + projectName + "/SLC"
#slcDir = scratchDir + '/SLC'
fn = os.listdir(slcDir)
slc_list0 = [os.path.basename(fname) for fname in sorted(fn)]
#slc_list0 = [os.path.basename(fname) for fname in sorted(glob.glob(slcDir + '/*'))]
slc_list = []
for k0 in slc_list0:
if is_number(k0):
slc_list.append(k0)
slc_list = sorted(slc_list)
return slc_list
def createBlankFile(strFile):
f = open(strFile,'w')
for i in range (10):
f.write('\n')
f.close()
def read_attr(fname):
# read hdf5
with h5py.File(fname, 'r') as f:
atr = dict(f.attrs)
return atr
def read_hdf5(fname, datasetName=None, box=None):
# read hdf5
with h5py.File(fname, 'r') as f:
data = f[datasetName][:]
atr = dict(f.attrs)
return data, atr
def get_dataNames(FILE):
with h5py.File(FILE, 'r') as f:
dataNames = []
for k0 in f.keys():
dataNames.append(k0)
return dataNames
def check_variable_name(path):
s=path.split("/")[0]
if len(s)>0 and s[0]=="$":
p0=os.getenv(s[1:])
path=path.replace(path.split("/")[0],p0)
return path
def read_template(File, delimiter='='):
'''Reads the template file into a python dictionary structure.
Input : string, full path to the template file
Output: dictionary, pysar template content
Example:
tmpl = read_template(KyushuT424F610_640AlosA.template)
tmpl = read_template(R1_54014_ST5_L0_F898.000.pi, ':')
'''
template_dict = {}
for line in open(File):
line = line.strip()
c = [i.strip() for i in line.split(delimiter, 1)] #split on the 1st occurrence of delimiter
if len(c) < 2 or line.startswith('%') or line.startswith('#'):
next #ignore commented lines or those without variables
else:
atrName = c[0]
atrValue = str.replace(c[1],'\n','').split("#")[0].strip()
atrValue = check_variable_name(atrValue)
template_dict[atrName] = atrValue
return template_dict
def read_gamma_par(inFile, task, keyword):
if task == "read":
f = open(inFile, "r")
while 1:
line = f.readline()
if not line: break
if line.count(keyword) == 1:
strtemp = line.split(":")
value = strtemp[1].strip()
return value
print("Keyword " + keyword + " doesn't exist in " + inFile)
f.close
def write_h5(datasetDict, out_file, metadata=None, ref_file=None, compression=None):
if os.path.isfile(out_file):
print('delete exsited file: {}'.format(out_file))
os.remove(out_file)
print('create HDF5 file: {} with w mode'.format(out_file))
dt = h5py.special_dtype(vlen=np.dtype('float64'))
with h5py.File(out_file, 'w') as f:
for dsName in datasetDict.keys():
data = datasetDict[dsName]
ds = f.create_dataset(dsName,
data=data,
compression=compression)
for key, value in metadata.items():
f.attrs[key] = str(value)
#print(key + ': ' + value)
print('finished writing to {}'.format(out_file))
return out_file
######################################################################
class progressBar:
"""Creates a text-based progress bar. Call the object with
the simple print command to see the progress bar, which looks
something like this:
[=======> 22% ]
You may specify the progress bar's min and max values on init.
note:
modified from mintPy (https://github.com/insarlab/MintPy/wiki)
Code originally from http://code.activestate.com/recipes/168639/
example:
from mintpy.utils import ptime
date12_list = ptime.list_ifgram2date12(ifgram_list)
prog_bar = ptime.progressBar(maxValue=1000, prefix='calculating:')
for i in range(1000):
prog_bar.update(i+1, suffix=date)
prog_bar.update(i+1, suffix=date12_list[i])
prog_bar.close()
"""
def __init__(self, maxValue=100, prefix='', minValue=0, totalWidth=70, print_msg=True):
self.prog_bar = "[]" # This holds the progress bar string
self.min = minValue
self.max = maxValue
self.span = maxValue - minValue
self.suffix = ''
self.prefix = prefix
self.print_msg = print_msg
## calculate total width based on console width
#rows, columns = os.popen('stty size', 'r').read().split()
#self.width = round(int(columns) * 0.7 / 10) * 10
self.width = totalWidth
self.reset()
def reset(self):
self.start_time = time.time()
self.amount = 0 # When amount == max, we are 100% done
self.update_amount(0) # Build progress bar string
def update_amount(self, newAmount=0, suffix=''):
""" Update the progress bar with the new amount (with min and max
values set at initialization; if it is over or under, it takes the
min or max value as a default. """
if newAmount < self.min:
newAmount = self.min
if newAmount > self.max:
newAmount = self.max
self.amount = newAmount
# Figure out the new percent done, round to an integer
diffFromMin = np.float(self.amount - self.min)
percentDone = (diffFromMin / np.float(self.span)) * 100.0
percentDone = np.int(np.round(percentDone))
# Figure out how many hash bars the percentage should be
allFull = self.width - 2 - 18
numHashes = (percentDone / 100.0) * allFull
numHashes = np.int(np.round(numHashes))
# Build a progress bar with an arrow of equal signs; special cases for
# empty and full
if numHashes == 0:
self.prog_bar = '%s[>%s]' % (self.prefix, ' '*(allFull-1))
elif numHashes == allFull:
self.prog_bar = '%s[%s]' % (self.prefix, '='*allFull)
if suffix:
self.prog_bar += ' %s' % (suffix)
else:
self.prog_bar = '[%s>%s]' % ('='*(numHashes-1), ' '*(allFull-numHashes))
# figure out where to put the percentage, roughly centered
percentPlace = int(len(self.prog_bar)/2 - len(str(percentDone)))
percentString = ' ' + str(percentDone) + '% '
# slice the percentage into the bar
self.prog_bar = ''.join([self.prog_bar[0:percentPlace],
percentString,
self.prog_bar[percentPlace+len(percentString):]])
# prefix and suffix
self.prog_bar = self.prefix + self.prog_bar
if suffix:
self.prog_bar += ' %s' % (suffix)
# time info - elapsed time and estimated remaining time
if percentDone > 0:
elapsed_time = time.time() - self.start_time
self.prog_bar += '%5ds / %5ds' % (int(elapsed_time),
int(elapsed_time * (100./percentDone-1)))
def update(self, value, every=1, suffix=''):
""" Updates the amount, and writes to stdout. Prints a
carriage return first, so it will overwrite the current
line in stdout."""
if value % every == 0 or value >= self.max:
self.update_amount(newAmount=value, suffix=suffix)
if self.print_msg:
sys.stdout.write('\r' + self.prog_bar)
sys.stdout.flush()
def close(self):
"""Prints a blank space at the end to ensure proper printing
of future statements."""
if self.print_msg:
print(' ')
@@ -0,0 +1,641 @@
############################################################
# Program is part of PyINT V2.1 #
# Copyright 2017-2019 Yunmeng Cao #
# Contact: ymcmrs@gmail.com #
############################################################
#from datetime import datetime
import datetime
import urllib.request
import os
import numpy as np
import random
import h5py
from pathlib import Path
import linecache
import time
import glob
from tqdm import tqdm
from concurrent.futures import ProcessPoolExecutor, as_completed
####################### update template #############################
def update_template(template_file):
templateDict = {}
######### download using SSARA ######
#templateDict['sensor'] = 'sentinel-1'
#templateDict['track'] = '14'
#templateDict['frame'] = '75'
templateDict['start_time'] = '1989-01-01'
templateDict['end_time'] = '2189-01-01'
####### basic parameters for interferometry ######
templateDict['start_swath'] = '1'
templateDict['end_swath'] = '3'
templateDict['start_burst'] = '1'
templateDict['end_burst'] = '20'
templateDict['dem_lat_ovr'] = '0.5' # get 30m resolution of lookup table, 0.5 to 60m, 2 to 15m
templateDict['dem_lon_ovr'] = '0.5' # get 30m resolution of lookup table
templateDict['Igram_Spsflg'] = '1' # Range spectral filtering
templateDict['Igram_Azfflg'] = '1' # Azimuth common band filtering
templateDict['rwin4cor'] = '256' # range window length for coregistration
templateDict['azwin4cor'] = '256' # azimuth window length for coregistration
templateDict['rsample4cor'] = '32' # range samples used for fitting the coregistration parameters
templateDict['azsample4cor'] = '32' # azimuth samples used for fitting the coregistration parameters
templateDict['thresh4cor'] = '0.15' # 2016 GAMMA or higher version, for 2015 GAMMA or lower version should be SNR
templateDict['coreCoarse'] = 'both' # initial coregistration method, [options: orbit, ampcor, both]
templateDict['coreMethod'] = 'DEM' # coregistration method [option: DEM, init] DEM means with DEM assistant
templateDict['Igram_Cor_rwin'] = '5' # used for cc_wave
templateDict['Igram_Cor_awin'] = '5' # used for cc_wave
templateDict['Igram_Cor_Win'] = '5' # used for adf
templateDict['adf_alpha'] = '0.4' # used for adf
######## sim phase ##################
templateDict['Igram_Flag_TDM'] = 'N'
templateDict['Simphase_rpos'] = '-'
templateDict['Simphase_azpos'] = '-'
templateDict['Simphase_rwin'] = '256'
templateDict['Simphase_azwin'] = '256'
templateDict['Simphase_thresh'] = '-'
#### unwrap phase ###########
templateDict['mcf_triangular'] = '0' # triangular type of mcf [0: regular; 1: delaunay;]
templateDict['unwrap_patr'] = '1'
templateDict['unwrap_pataz'] = '1'
templateDict['unwrapThreshold'] = '0.1' # minimum coherence used for unwrap
#### geocode #########
templateDict['geo_interp'] = '0' # [0: nearest; 1: bicubic spline]
############## interferometry ################
templateDict['int_flag'] = '1' # 1 means do interferometry
templateDict['diff_flag'] = '1' # differential process, i.e., remove DEM phase
templateDict['unw_flag'] = '1' # unwrap process
templateDict['geo_flag'] = '0' # geocode process
############## select network #############
templateDict['endDate'] = '21000101'
templateDict['startDate'] = '19000101'
templateDict['network_method'] = 'sbas' # sbas, sequential, delaunay, stars
templateDict['conNumb'] = '2' # connect number for sequential
templateDict['max_tb'] = '50000'
templateDict['max_sb'] = '50000'
############## time-series ################
templateDict['download_data'] = '0' # if 1, track, frame, or time informations should be provided
templateDict['down_parallel'] = '1' # multi-processor number used for downloading
templateDict['raw2slc_all'] = '0' # i.e., download 2 slc
templateDict['raw2slc_all_parallel'] = '1' # multi-processor number used
templateDict['extract_burst_all'] = '0' # for TOPS SLC only
templateDict['extract_all_parallel'] = '1' # multi-processor number used
templateDict['coreg_all'] = '1'
templateDict['coreg_all_parallel'] = '1' # multi-processor number used [4 or 8]
templateDict['select_pairs'] = '1'
templateDict['diff_all'] = '1'
templateDict['diff_all_parallel'] = '1' # multi-processor number used [4 or 8]
templateDict['unwrap_all'] = '1'
templateDict['unwrap_all_parallel'] = '1' # multi-processor number used [8 or 10]
templateDict['geocode_all'] = '0'
templateDict['geocode_all_parallel'] = '1' # multi-processor number used
templateDict['load_data'] = '0' # loading data for mintpy processing
templateDict0 = read_template(template_file, delimiter='=')
for key, value in templateDict0.items():
templateDict[key] = str(value)
return templateDict
####################### time-related function ################
def is_number(s):
try:
int(s)
return True
except ValueError:
return False
def print_process_time(start, end):
hours, rem = divmod(end-start, 3600)
minutes, seconds = divmod(rem, 60)
print("Total process time: "+"{:0>2}:{:0>2}:{:05.2f}".format(int(hours),int(minutes),seconds))
return
def date_add1d(date0):
format_str = '%Y%m%d' # The format
date_obj = datetime.datetime.strptime(date0,format_str)
date1 = (date_obj + datetime.timedelta(days=1)).date().strftime('%Y%m%d')
return date1
def date_minus1d(date0):
format_str = '%Y%m%d' # The format
date_obj = datetime.datetime.strptime(date0,format_str)
date1 = (date_obj - datetime.timedelta(days=1)).date().strftime('%Y%m%d')
return date1
def generate_random_name(sufix):
nowTime = datetime.datetime.now().strftime("%Y%m%d%H%M%S") #generate the present time
randomNum = random.randint(0,100)
randomNum1 = random.randint(0,100)
Nm = nowTime + str(randomNum)+ str(randomNum1) + sufix
return Nm
def yyyymmdd2yyyyddd(date):
dt = datetime.datetime.strptime(date, "%Y%m%d") # get datetime object
day_of_year = (dt - datetime.datetime(dt.year, 1, 1)) # Jan the 1st is day 1
doy = day_of_year.days + 1
year = dt.year
doy = str(doy)
if len(doy) ==1:
doy = '00' + doy
elif len(doy) ==2:
doy ='0'+ doy
year = str(year)
return year, doy
def get_txt_lines(txt):
count=0
myfile=open(txt,"r")
for line in myfile:
count=count+1
return count
def read_txt2list(txt):
A = np.loadtxt(txt,dtype=np.str)
if np.array(A).size ==1:
A = [A]
elif isinstance(A[0],bytes):
A = A.astype(str)
A = list(A)
return A
def read_txt2array(txt):
A = np.loadtxt(txt,dtype=np.str)
if np.array(A).size ==1:
A = [A]
elif isinstance(A[0],bytes):
A = A.astype(str)
#A = list(A)
return A
def get_sardata_swath(start_swath,end_swath):
k_swath = '0'
if (start_swath == '1') and (end_swath == '1'):
k_swath = '1'
elif (start_swath == '2') and (end_swath == '2'):
k_swath = '2'
elif (start_swath == '3') and (end_swath == '3'):
k_swath = '3'
elif (start_swath == '1') and (end_swath == '2'):
k_swath = '4'
elif (start_swath == '2') and (end_swath == '3'):
k_swath = '5'
elif (start_swath == '1') and (end_swath == '3'):
k_swath = '0'
return k_swath
def get_filelist_filesize(url0):
ttt = generate_random_name('.txt')
call_str = 'curl -s ' + url0 + ' > ' + ttt
os.system(call_str)
A = read_txt2array(ttt)
A_size = A[:,4]
A_size = A_size.astype(int)
A_size = A_size/1024/1024 #bytes to Mb
A_name = A[:,8]
if os.path.isfile(ttt):
os.remove(ttt)
return A_name, A_size
def yyyymmdd(date0):
if len(date0) ==6:
if float(date0[0:2]) > 90:
date1 = '19' + date0
else:
date1 = '20' + date0
elif len(date0) ==8:
date1 = date0
else:
print('The input date is invalid!!')
date1 = ''
return date1
def yymmdd(date0):
if len(date0) ==6:
date1 = date0
elif len(date0) ==8:
date1 = date0[2:8]
else:
print('The input date is invalid!!')
date1 = ''
return date1
def parallel_process(array, function, n_jobs=16, use_kwargs=False):
"""
A parallel version of the map function with a progress bar.
Args:
array (array-like): An array to iterate over.
function (function): A python function to apply to the elements of array
n_jobs (int, default=16): The number of cores to use
use_kwargs (boolean, default=False): Whether to consider the elements of array as dictionaries of
keyword arguments to function
Returns:
[function(array[0]), function(array[1]), ...]
"""
#We run the first few iterations serially to catch bugs
#If we set n_jobs to 1, just run a list comprehension. This is useful for benchmarking and debugging.
if n_jobs==1:
return [function(**a) if use_kwargs else function(a) for a in tqdm(array[:])]
#Assemble the workers
with ProcessPoolExecutor(max_workers=n_jobs) as pool:
#Pass the elements of array into function
if use_kwargs:
futures = [pool.submit(function, **a) for a in array[:]]
else:
futures = [pool.submit(function, a) for a in array[:]]
kwargs = {
'total': len(futures),
'unit': 'it',
'unit_scale': True,
'leave': True
}
#Print out the progress as tasks complete
for f in tqdm(as_completed(futures), **kwargs):
pass
out = []
#Get the results from the futures.
for i, future in tqdm(enumerate(futures)):
try:
out.append(future.result())
except Exception as e:
out.append(e)
return out
def sort_unique_list(numb_list):
list_out = sorted(set(numb_list))
return list_out
############################# download data ###################################
def StrNum(S):
S = str(S)
if len(S)==1:
S='0' +S
return S
def download_s1_orbit(date,save_path,satellite='A'):
DATE = date
if len(DATE)==6:
DATE = '20' + DATE
ST = satellite
YEAR = int(DATE[0:4])
MON = int(DATE[4:6])
DAY = int(DATE[6:8])
MON_DAY = [31,28,31,30,31,30,31,31,30,31,30,31]
if YEAR%4==0:
MON_DAY[1]=29
if MON ==1 and DAY ==1:
DAY0 = 31
MON0 = 12
YEAR0 =YEAR -1
elif MON!=1 and DAY ==1:
DAY0 = MON_DAY[MON-2]
MON0 = MON-1
YEAR0 = YEAR
else:
DAY0 = DAY -1
MON0 = MON
YEAR0 = YEAR
MONDAY0 = MON_DAY[MON0-1]
TT = [1,4,7,10,13,16,19,22,25,28,MONDAY0]
T0 = []
for k in range(len(TT)):
T0.append(TT[k])
TT[k] = TT[k]-DAY0
for k in range(len(TT)):
if k == len(TT)-1:
if TT[k]==0:
ff = k-1
else:
if TT[k]<=0 and TT[k+1]>0:
ff = k
DAY1 = T0[ff]
DAY2 = T0[ff+1]
S1 = StrNum(YEAR0) + '-' + StrNum(MON0)
S2 = StrNum(YEAR0) + '-' + StrNum(MON0) + '-' + StrNum(DAY1)
S3 = StrNum(YEAR0) + '-' + StrNum(MON0) + '-' + StrNum(DAY2)
S4 = StrNum(YEAR0) + '-' + StrNum(MON0) + '-' + StrNum(DAY0)
#SS = 'https://qc.sentinel1.eo.esa.int/aux_poeorb/?mission=S1' + ST + '&validity_start_time=' + StrNum(YEAR0) + '&validity_start_time=' + S1 + '&validity_start_time=' + S2 + '..' + S3 + '&validity_start_time=' + S4
SS = 'https://qc.sentinel1.eo.esa.int/aux_poeorb/?validity_start=' + StrNum(YEAR0) + '&validity_start=' + S1 + '&validity_start=' + S2 + '..' + S3 + '&validity_start=' +S4 + '&sentinel1__mission=S1'+ST+ '&sentinel1_mission=S1'+ST+ '&sentinel1_mission=S1'+ST+ '&sentinel1_mission=S1'+ST
tt ='tt_orb_' + date
tt0 ='tt0_orb_' + date
tt00 ='tt00_orb_' + date
tt000 ='tt000_orb_' + date
SS = "'" + SS + "'"
#print(SS)
call_str = 'curl -s -l ' + SS + ' > ' + tt
os.system(call_str)
call_str = "grep 'EOF' -C 0 " + tt + " >" + tt0
os.system(call_str)
call_str="awk -F'href=' '{print $2}' " + tt0 +' >' + tt00
os.system(call_str)
call_str= "awk -F'>' '{print $1}' " + tt00 + '> ' + tt000
os.system(call_str)
SS=linecache.getline(tt000, 1)
SS = SS.split('"')[-1]
filename = os.path.basename(SS)
# filename = os.path.basename(SS)
# SS1 = save_path + '/' + filename
# if os.path.isfile(SS1):
# if os.path.getsize(SS1) > 4409000:
# call_str = "downlaod the precise Orbit of" + date
# print(call_str)
# else:
# call_str = 'wget -q --no-check-certificate ' + SS + ' -O ' + save_path + '/' +filename
# os.system(call_str)
# call_str = "downlaod the precise Orbit of" + date
# print(call_str)
# else:
# call_str = 'wget -q --no-check-certificate ' + SS + ' -O ' + save_path + '/' +filename
# os.system(call_str)
# call_str = "downlaod the precise Orbit of" + date
# print(call_str)
# if not os.path.isfile(filename):
call_str = 'wget -q --no-check-certificate ' + SS + ' -O ' + save_path + '/' +filename
os.system(call_str)
call_str = "downlaod the precise Orbit of" + date
print(call_str)
filename = os.path.basename(SS)
os.remove(tt)
os.remove(tt0)
os.remove(tt00)
os.remove(tt000)
return filename
############################# write & read #####################################
def copy_file(file0,file1):
call_str = 'cp ' + file0 + ' ' + file1
os.system(call_str)
return
def get_project_slcList(projectName):
scratchDir = os.getenv('SCRATCHDIR')
slcDir = scratchDir + '/' + projectName + "/SLC"
#slcDir = scratchDir + '/SLC'
fn = os.listdir(slcDir)
slc_list0 = [os.path.basename(fname) for fname in sorted(fn)]
#slc_list0 = [os.path.basename(fname) for fname in sorted(glob.glob(slcDir + '/*'))]
slc_list = []
for k0 in slc_list0:
if is_number(k0):
slc_list.append(k0)
slc_list = sorted(slc_list)
return slc_list
def createBlankFile(strFile):
f = open(strFile,'w')
for i in range (10):
f.write('\n')
f.close()
def read_attr(fname):
# read hdf5
with h5py.File(fname, 'r') as f:
atr = dict(f.attrs)
return atr
def read_hdf5(fname, datasetName=None, box=None):
# read hdf5
with h5py.File(fname, 'r') as f:
data = f[datasetName][:]
atr = dict(f.attrs)
return data, atr
def get_dataNames(FILE):
with h5py.File(FILE, 'r') as f:
dataNames = []
for k0 in f.keys():
dataNames.append(k0)
return dataNames
def check_variable_name(path):
s=path.split("/")[0]
if len(s)>0 and s[0]=="$":
p0=os.getenv(s[1:])
path=path.replace(path.split("/")[0],p0)
return path
def read_template(File, delimiter='='):
'''Reads the template file into a python dictionary structure.
Input : string, full path to the template file
Output: dictionary, pysar template content
Example:
tmpl = read_template(KyushuT424F610_640AlosA.template)
tmpl = read_template(R1_54014_ST5_L0_F898.000.pi, ':')
'''
template_dict = {}
for line in open(File):
line = line.strip()
c = [i.strip() for i in line.split(delimiter, 1)] #split on the 1st occurrence of delimiter
if len(c) < 2 or line.startswith('%') or line.startswith('#'):
next #ignore commented lines or those without variables
else:
atrName = c[0]
atrValue = str.replace(c[1],'\n','').split("#")[0].strip()
atrValue = check_variable_name(atrValue)
template_dict[atrName] = atrValue
return template_dict
def read_gamma_par(inFile, task, keyword):
if task == "read":
f = open(inFile, "r")
while 1:
line = f.readline()
if not line: break
if line.count(keyword) == 1:
strtemp = line.split(":")
value = strtemp[1].strip()
return value
print("Keyword " + keyword + " doesn't exist in " + inFile)
f.close
def write_h5(datasetDict, out_file, metadata=None, ref_file=None, compression=None):
if os.path.isfile(out_file):
print('delete exsited file: {}'.format(out_file))
os.remove(out_file)
print('create HDF5 file: {} with w mode'.format(out_file))
dt = h5py.special_dtype(vlen=np.dtype('float64'))
with h5py.File(out_file, 'w') as f:
for dsName in datasetDict.keys():
data = datasetDict[dsName]
ds = f.create_dataset(dsName,
data=data,
compression=compression)
for key, value in metadata.items():
f.attrs[key] = str(value)
#print(key + ': ' + value)
print('finished writing to {}'.format(out_file))
return out_file
######################################################################
class progressBar:
"""Creates a text-based progress bar. Call the object with
the simple print command to see the progress bar, which looks
something like this:
[=======> 22% ]
You may specify the progress bar's min and max values on init.
note:
modified from mintPy (https://github.com/insarlab/MintPy/wiki)
Code originally from http://code.activestate.com/recipes/168639/
example:
from mintpy.utils import ptime
date12_list = ptime.list_ifgram2date12(ifgram_list)
prog_bar = ptime.progressBar(maxValue=1000, prefix='calculating:')
for i in range(1000):
prog_bar.update(i+1, suffix=date)
prog_bar.update(i+1, suffix=date12_list[i])
prog_bar.close()
"""
def __init__(self, maxValue=100, prefix='', minValue=0, totalWidth=70, print_msg=True):
self.prog_bar = "[]" # This holds the progress bar string
self.min = minValue
self.max = maxValue
self.span = maxValue - minValue
self.suffix = ''
self.prefix = prefix
self.print_msg = print_msg
## calculate total width based on console width
#rows, columns = os.popen('stty size', 'r').read().split()
#self.width = round(int(columns) * 0.7 / 10) * 10
self.width = totalWidth
self.reset()
def reset(self):
self.start_time = time.time()
self.amount = 0 # When amount == max, we are 100% done
self.update_amount(0) # Build progress bar string
def update_amount(self, newAmount=0, suffix=''):
""" Update the progress bar with the new amount (with min and max
values set at initialization; if it is over or under, it takes the
min or max value as a default. """
if newAmount < self.min:
newAmount = self.min
if newAmount > self.max:
newAmount = self.max
self.amount = newAmount
# Figure out the new percent done, round to an integer
diffFromMin = np.float(self.amount - self.min)
percentDone = (diffFromMin / np.float(self.span)) * 100.0
percentDone = np.int(np.round(percentDone))
# Figure out how many hash bars the percentage should be
allFull = self.width - 2 - 18
numHashes = (percentDone / 100.0) * allFull
numHashes = np.int(np.round(numHashes))
# Build a progress bar with an arrow of equal signs; special cases for
# empty and full
if numHashes == 0:
self.prog_bar = '%s[>%s]' % (self.prefix, ' '*(allFull-1))
elif numHashes == allFull:
self.prog_bar = '%s[%s]' % (self.prefix, '='*allFull)
if suffix:
self.prog_bar += ' %s' % (suffix)
else:
self.prog_bar = '[%s>%s]' % ('='*(numHashes-1), ' '*(allFull-numHashes))
# figure out where to put the percentage, roughly centered
percentPlace = int(len(self.prog_bar)/2 - len(str(percentDone)))
percentString = ' ' + str(percentDone) + '% '
# slice the percentage into the bar
self.prog_bar = ''.join([self.prog_bar[0:percentPlace],
percentString,
self.prog_bar[percentPlace+len(percentString):]])
# prefix and suffix
self.prog_bar = self.prefix + self.prog_bar
if suffix:
self.prog_bar += ' %s' % (suffix)
# time info - elapsed time and estimated remaining time
if percentDone > 0:
elapsed_time = time.time() - self.start_time
self.prog_bar += '%5ds / %5ds' % (int(elapsed_time),
int(elapsed_time * (100./percentDone-1)))
def update(self, value, every=1, suffix=''):
""" Updates the amount, and writes to stdout. Prints a
carriage return first, so it will overwrite the current
line in stdout."""
if value % every == 0 or value >= self.max:
self.update_amount(newAmount=value, suffix=suffix)
if self.print_msg:
sys.stdout.write('\r' + self.prog_bar)
sys.stdout.flush()
def close(self):
"""Prints a blank space at the end to ensure proper printing
of future statements."""
if self.print_msg:
print(' ')
@@ -0,0 +1,623 @@
############################################################
# Program is part of PyINT V2.1 #
# Copyright 2017-2019 Yunmeng Cao #
# Contact: ymcmrs@gmail.com #
############################################################
#from datetime import datetime
import datetime
import urllib.request
import os
import numpy as np
import random
import h5py
from pathlib import Path
import linecache
import time
import glob
from tqdm import tqdm
from concurrent.futures import ProcessPoolExecutor, as_completed
####################### update template #############################
def update_template(template_file):
templateDict = {}
######### download using SSARA ######
#templateDict['sensor'] = 'sentinel-1'
#templateDict['track'] = '14'
#templateDict['frame'] = '75'
templateDict['start_time'] = '1989-01-01'
templateDict['end_time'] = '2189-01-01'
####### basic parameters for interferometry ######
templateDict['start_swath'] = '1'
templateDict['end_swath'] = '3'
templateDict['start_burst'] = '1'
templateDict['end_burst'] = '20'
templateDict['dem_lat_ovr'] = '0.5' # get 30m resolution of lookup table, 0.5 to 60m, 2 to 15m
templateDict['dem_lon_ovr'] = '0.5' # get 30m resolution of lookup table
templateDict['Igram_Spsflg'] = '1' # Range spectral filtering
templateDict['Igram_Azfflg'] = '1' # Azimuth common band filtering
templateDict['rwin4cor'] = '256' # range window length for coregistration
templateDict['azwin4cor'] = '256' # azimuth window length for coregistration
templateDict['rsample4cor'] = '32' # range samples used for fitting the coregistration parameters
templateDict['azsample4cor'] = '32' # azimuth samples used for fitting the coregistration parameters
templateDict['thresh4cor'] = '0.15' # 2016 GAMMA or higher version, for 2015 GAMMA or lower version should be SNR
templateDict['coreCoarse'] = 'both' # initial coregistration method, [options: orbit, ampcor, both]
templateDict['coreMethod'] = 'DEM' # coregistration method [option: DEM, init] DEM means with DEM assistant
templateDict['Igram_Cor_rwin'] = '5' # used for cc_wave
templateDict['Igram_Cor_awin'] = '5' # used for cc_wave
templateDict['Igram_Cor_Win'] = '5' # used for adf
templateDict['adf_alpha'] = '0.4' # used for adf
######## sim phase ##################
templateDict['Igram_Flag_TDM'] = 'N'
templateDict['Simphase_rpos'] = '-'
templateDict['Simphase_azpos'] = '-'
templateDict['Simphase_rwin'] = '256'
templateDict['Simphase_azwin'] = '256'
templateDict['Simphase_thresh'] = '-'
#### unwrap phase ###########
templateDict['mcf_triangular'] = '0' # triangular type of mcf [0: regular; 1: delaunay;]
templateDict['unwrap_patr'] = '1'
templateDict['unwrap_pataz'] = '1'
templateDict['unwrapThreshold'] = '0.1' # minimum coherence used for unwrap
#### geocode #########
templateDict['geo_interp'] = '0' # [0: nearest; 1: bicubic spline]
############## interferometry ################
templateDict['int_flag'] = '1' # 1 means do interferometry
templateDict['diff_flag'] = '1' # differential process, i.e., remove DEM phase
templateDict['unw_flag'] = '1' # unwrap process
templateDict['geo_flag'] = '0' # geocode process
############## select network #############
templateDict['endDate'] = '21000101'
templateDict['startDate'] = '19000101'
templateDict['network_method'] = 'sbas' # sbas, sequential, delaunay, stars
templateDict['conNumb'] = '2' # connect number for sequential
templateDict['max_tb'] = '50000'
templateDict['max_sb'] = '50000'
############## time-series ################
templateDict['download_data'] = '0' # if 1, track, frame, or time informations should be provided
templateDict['down_parallel'] = '1' # multi-processor number used for downloading
templateDict['raw2slc_all'] = '0' # i.e., download 2 slc
templateDict['raw2slc_all_parallel'] = '1' # multi-processor number used
templateDict['extract_burst_all'] = '0' # for TOPS SLC only
templateDict['extract_all_parallel'] = '1' # multi-processor number used
templateDict['coreg_all'] = '1'
templateDict['coreg_all_parallel'] = '1' # multi-processor number used [4 or 8]
templateDict['select_pairs'] = '1'
templateDict['diff_all'] = '1'
templateDict['diff_all_parallel'] = '1' # multi-processor number used [4 or 8]
templateDict['unwrap_all'] = '1'
templateDict['unwrap_all_parallel'] = '1' # multi-processor number used [8 or 10]
templateDict['geocode_all'] = '0'
templateDict['geocode_all_parallel'] = '1' # multi-processor number used
templateDict['load_data'] = '0' # loading data for mintpy processing
templateDict0 = read_template(template_file, delimiter='=')
for key, value in templateDict0.items():
templateDict[key] = str(value)
return templateDict
####################### time-related function ################
def is_number(s):
try:
int(s)
return True
except ValueError:
return False
def print_process_time(start, end):
hours, rem = divmod(end-start, 3600)
minutes, seconds = divmod(rem, 60)
print("Total process time: "+"{:0>2}:{:0>2}:{:05.2f}".format(int(hours),int(minutes),seconds))
return
def date_add1d(date0):
format_str = '%Y%m%d' # The format
date_obj = datetime.datetime.strptime(date0,format_str)
date1 = (date_obj + datetime.timedelta(days=1)).date().strftime('%Y%m%d')
return date1
def date_minus1d(date0):
format_str = '%Y%m%d' # The format
date_obj = datetime.datetime.strptime(date0,format_str)
date1 = (date_obj - datetime.timedelta(days=1)).date().strftime('%Y%m%d')
return date1
def generate_random_name(sufix):
nowTime = datetime.datetime.now().strftime("%Y%m%d%H%M%S") #generate the present time
randomNum = random.randint(0,100)
randomNum1 = random.randint(0,100)
Nm = nowTime + str(randomNum)+ str(randomNum1) + sufix
return Nm
def yyyymmdd2yyyyddd(date):
dt = datetime.datetime.strptime(date, "%Y%m%d") # get datetime object
day_of_year = (dt - datetime.datetime(dt.year, 1, 1)) # Jan the 1st is day 1
doy = day_of_year.days + 1
year = dt.year
doy = str(doy)
if len(doy) ==1:
doy = '00' + doy
elif len(doy) ==2:
doy ='0'+ doy
year = str(year)
return year, doy
def get_txt_lines(txt):
count=0
myfile=open(txt,"r")
for line in myfile:
count=count+1
return count
def read_txt2list(txt):
A = np.loadtxt(txt,dtype=np.str)
if np.array(A).size ==1:
A = [A]
elif isinstance(A[0],bytes):
A = A.astype(str)
A = list(A)
return A
def read_txt2array(txt):
A = np.loadtxt(txt,dtype=np.str)
if np.array(A).size ==1:
A = [A]
elif isinstance(A[0],bytes):
A = A.astype(str)
#A = list(A)
return A
def get_sardata_swath(start_swath,end_swath):
k_swath = '0'
if (start_swath == '1') and (end_swath == '1'):
k_swath = '1'
elif (start_swath == '2') and (end_swath == '2'):
k_swath = '2'
elif (start_swath == '3') and (end_swath == '3'):
k_swath = '3'
elif (start_swath == '1') and (end_swath == '2'):
k_swath = '4'
elif (start_swath == '2') and (end_swath == '3'):
k_swath = '5'
elif (start_swath == '2') and (end_swath == '3'):
k_swath = '-'
return k_swath
def get_filelist_filesize(url0):
ttt = generate_random_name('.txt')
call_str = 'curl -s ' + url0 + ' > ' + ttt
os.system(call_str)
A = read_txt2array(ttt)
A_size = A[:,4]
A_size = A_size.astype(int)
A_size = A_size/1024/1024 #bytes to Mb
A_name = A[:,8]
if os.path.isfile(ttt):
os.remove(ttt)
return A_name, A_size
def yyyymmdd(date0):
if len(date0) ==6:
if float(date0[0:2]) > 90:
date1 = '19' + date0
else:
date1 = '20' + date0
elif len(date0) ==8:
date1 = date0
else:
print('The input date is invalid!!')
date1 = ''
return date1
def yymmdd(date0):
if len(date0) ==6:
date1 = date0
elif len(date0) ==8:
date1 = date0[2:8]
else:
print('The input date is invalid!!')
date1 = ''
return date1
def parallel_process(array, function, n_jobs=16, use_kwargs=False):
"""
A parallel version of the map function with a progress bar.
Args:
array (array-like): An array to iterate over.
function (function): A python function to apply to the elements of array
n_jobs (int, default=16): The number of cores to use
use_kwargs (boolean, default=False): Whether to consider the elements of array as dictionaries of
keyword arguments to function
Returns:
[function(array[0]), function(array[1]), ...]
"""
#We run the first few iterations serially to catch bugs
#If we set n_jobs to 1, just run a list comprehension. This is useful for benchmarking and debugging.
if n_jobs==1:
return [function(**a) if use_kwargs else function(a) for a in tqdm(array[:])]
#Assemble the workers
with ProcessPoolExecutor(max_workers=n_jobs) as pool:
#Pass the elements of array into function
if use_kwargs:
futures = [pool.submit(function, **a) for a in array[:]]
else:
futures = [pool.submit(function, a) for a in array[:]]
kwargs = {
'total': len(futures),
'unit': 'it',
'unit_scale': True,
'leave': True
}
#Print out the progress as tasks complete
for f in tqdm(as_completed(futures), **kwargs):
pass
out = []
#Get the results from the futures.
for i, future in tqdm(enumerate(futures)):
try:
out.append(future.result())
except Exception as e:
out.append(e)
return out
def sort_unique_list(numb_list):
list_out = sorted(set(numb_list))
return list_out
############################# download data ###################################
def StrNum(S):
S = str(S)
if len(S)==1:
S='0' +S
return S
def download_s1_orbit(date,save_path,satellite='A'):
DATE = date
if len(DATE)==6:
DATE = '20' + DATE
ST = satellite
YEAR = int(DATE[0:4])
MON = int(DATE[4:6])
DAY = int(DATE[6:8])
MON_DAY = [31,28,31,30,31,30,31,31,30,31,30,31]
if YEAR%4==0:
MON_DAY[1]=29
if MON ==1 and DAY ==1:
DAY0 = 31
MON0 = 12
YEAR0 =YEAR -1
elif MON!=1 and DAY ==1:
DAY0 = MON_DAY[MON-2]
MON0 = MON-1
YEAR0 = YEAR
else:
DAY0 = DAY -1
MON0 = MON
YEAR0 = YEAR
MONDAY0 = MON_DAY[MON0-1]
TT = [1,4,7,10,13,16,19,22,25,28,MONDAY0]
T0 = []
for k in range(len(TT)):
T0.append(TT[k])
TT[k] = TT[k]-DAY0
for k in range(len(TT)):
if k == len(TT)-1:
if TT[k]==0:
ff = k-1
else:
if TT[k]<=0 and TT[k+1]>0:
ff = k
DAY1 = T0[ff]
DAY2 = T0[ff+1]
S1 = StrNum(YEAR0) + '-' + StrNum(MON0)
S2 = StrNum(YEAR0) + '-' + StrNum(MON0) + '-' + StrNum(DAY1)
S3 = StrNum(YEAR0) + '-' + StrNum(MON0) + '-' + StrNum(DAY2)
S4 = StrNum(YEAR0) + '-' + StrNum(MON0) + '-' + StrNum(DAY0)
#SS = 'https://qc.sentinel1.eo.esa.int/aux_poeorb/?mission=S1' + ST + '&validity_start_time=' + StrNum(YEAR0) + '&validity_start_time=' + S1 + '&validity_start_time=' + S2 + '..' + S3 + '&validity_start_time=' + S4
SS = 'https://qc.sentinel1.eo.esa.int/aux_poeorb/?validity_start=' + StrNum(YEAR0) + '&validity_start=' + S1 + '&validity_start=' + S2 + '..' + S3 + '&validity_start=' +S4 + '&sentinel1__mission=S1'+ST+ '&sentinel1_mission=S1'+ST+ '&sentinel1_mission=S1'+ST+ '&sentinel1_mission=S1'+ST
tt ='tt_orb_' + date
tt0 ='tt0_orb_' + date
tt00 ='tt00_orb_' + date
tt000 ='tt000_orb_' + date
SS = "'" + SS + "'"
#print(SS)
call_str = 'curl -s -l ' + SS + ' > ' + tt
os.system(call_str)
call_str = "grep 'EOF' -C 0 " + tt + " >" + tt0
os.system(call_str)
call_str="awk -F'href=' '{print $2}' " + tt0 +' >' + tt00
os.system(call_str)
call_str= "awk -F'>' '{print $1}' " + tt00 + '> ' + tt000
os.system(call_str)
SS=linecache.getline(tt000, 1)
SS = SS.split('"')[-1]
filename = os.path.basename(SS)
call_str = 'wget -q --no-check-certificate ' + SS + ' -O ' + save_path + '/' +filename
os.system(call_str)
call_str = "downlaod the precise Orbit of" + date
print(call_str)
filename = os.path.basename(SS)
os.remove(tt)
os.remove(tt0)
os.remove(tt00)
os.remove(tt000)
return filename
############################# write & read #####################################
def copy_file(file0,file1):
call_str = 'cp ' + file0 + ' ' + file1
os.system(call_str)
return
def get_project_slcList(projectName):
scratchDir = os.getenv('SCRATCHDIR')
slcDir = scratchDir + '/' + projectName + "/SLC"
#slcDir = scratchDir + '/SLC'
fn = os.listdir(slcDir)
slc_list0 = [os.path.basename(fname) for fname in sorted(fn)]
#slc_list0 = [os.path.basename(fname) for fname in sorted(glob.glob(slcDir + '/*'))]
slc_list = []
for k0 in slc_list0:
if is_number(k0):
slc_list.append(k0)
slc_list = sorted(slc_list)
return slc_list
def createBlankFile(strFile):
f = open(strFile,'w')
for i in range (10):
f.write('\n')
f.close()
def read_attr(fname):
# read hdf5
with h5py.File(fname, 'r') as f:
atr = dict(f.attrs)
return atr
def read_hdf5(fname, datasetName=None, box=None):
# read hdf5
with h5py.File(fname, 'r') as f:
data = f[datasetName][:]
atr = dict(f.attrs)
return data, atr
def get_dataNames(FILE):
with h5py.File(FILE, 'r') as f:
dataNames = []
for k0 in f.keys():
dataNames.append(k0)
return dataNames
def check_variable_name(path):
s=path.split("/")[0]
if len(s)>0 and s[0]=="$":
p0=os.getenv(s[1:])
path=path.replace(path.split("/")[0],p0)
return path
def read_template(File, delimiter='='):
'''Reads the template file into a python dictionary structure.
Input : string, full path to the template file
Output: dictionary, pysar template content
Example:
tmpl = read_template(KyushuT424F610_640AlosA.template)
tmpl = read_template(R1_54014_ST5_L0_F898.000.pi, ':')
'''
template_dict = {}
for line in open(File):
line = line.strip()
c = [i.strip() for i in line.split(delimiter, 1)] #split on the 1st occurrence of delimiter
if len(c) < 2 or line.startswith('%') or line.startswith('#'):
next #ignore commented lines or those without variables
else:
atrName = c[0]
atrValue = str.replace(c[1],'\n','').split("#")[0].strip()
atrValue = check_variable_name(atrValue)
template_dict[atrName] = atrValue
return template_dict
def read_gamma_par(inFile, task, keyword):
if task == "read":
f = open(inFile, "r")
while 1:
line = f.readline()
if not line: break
if line.count(keyword) == 1:
strtemp = line.split(":")
value = strtemp[1].strip()
return value
print("Keyword " + keyword + " doesn't exist in " + inFile)
f.close
def write_h5(datasetDict, out_file, metadata=None, ref_file=None, compression=None):
if os.path.isfile(out_file):
print('delete exsited file: {}'.format(out_file))
os.remove(out_file)
print('create HDF5 file: {} with w mode'.format(out_file))
dt = h5py.special_dtype(vlen=np.dtype('float64'))
with h5py.File(out_file, 'w') as f:
for dsName in datasetDict.keys():
data = datasetDict[dsName]
ds = f.create_dataset(dsName,
data=data,
compression=compression)
for key, value in metadata.items():
f.attrs[key] = str(value)
#print(key + ': ' + value)
print('finished writing to {}'.format(out_file))
return out_file
######################################################################
class progressBar:
"""Creates a text-based progress bar. Call the object with
the simple print command to see the progress bar, which looks
something like this:
[=======> 22% ]
You may specify the progress bar's min and max values on init.
note:
modified from mintPy (https://github.com/insarlab/MintPy/wiki)
Code originally from http://code.activestate.com/recipes/168639/
example:
from mintpy.utils import ptime
date12_list = ptime.list_ifgram2date12(ifgram_list)
prog_bar = ptime.progressBar(maxValue=1000, prefix='calculating:')
for i in range(1000):
prog_bar.update(i+1, suffix=date)
prog_bar.update(i+1, suffix=date12_list[i])
prog_bar.close()
"""
def __init__(self, maxValue=100, prefix='', minValue=0, totalWidth=70, print_msg=True):
self.prog_bar = "[]" # This holds the progress bar string
self.min = minValue
self.max = maxValue
self.span = maxValue - minValue
self.suffix = ''
self.prefix = prefix
self.print_msg = print_msg
## calculate total width based on console width
#rows, columns = os.popen('stty size', 'r').read().split()
#self.width = round(int(columns) * 0.7 / 10) * 10
self.width = totalWidth
self.reset()
def reset(self):
self.start_time = time.time()
self.amount = 0 # When amount == max, we are 100% done
self.update_amount(0) # Build progress bar string
def update_amount(self, newAmount=0, suffix=''):
""" Update the progress bar with the new amount (with min and max
values set at initialization; if it is over or under, it takes the
min or max value as a default. """
if newAmount < self.min:
newAmount = self.min
if newAmount > self.max:
newAmount = self.max
self.amount = newAmount
# Figure out the new percent done, round to an integer
diffFromMin = np.float(self.amount - self.min)
percentDone = (diffFromMin / np.float(self.span)) * 100.0
percentDone = np.int(np.round(percentDone))
# Figure out how many hash bars the percentage should be
allFull = self.width - 2 - 18
numHashes = (percentDone / 100.0) * allFull
numHashes = np.int(np.round(numHashes))
# Build a progress bar with an arrow of equal signs; special cases for
# empty and full
if numHashes == 0:
self.prog_bar = '%s[>%s]' % (self.prefix, ' '*(allFull-1))
elif numHashes == allFull:
self.prog_bar = '%s[%s]' % (self.prefix, '='*allFull)
if suffix:
self.prog_bar += ' %s' % (suffix)
else:
self.prog_bar = '[%s>%s]' % ('='*(numHashes-1), ' '*(allFull-numHashes))
# figure out where to put the percentage, roughly centered
percentPlace = int(len(self.prog_bar)/2 - len(str(percentDone)))
percentString = ' ' + str(percentDone) + '% '
# slice the percentage into the bar
self.prog_bar = ''.join([self.prog_bar[0:percentPlace],
percentString,
self.prog_bar[percentPlace+len(percentString):]])
# prefix and suffix
self.prog_bar = self.prefix + self.prog_bar
if suffix:
self.prog_bar += ' %s' % (suffix)
# time info - elapsed time and estimated remaining time
if percentDone > 0:
elapsed_time = time.time() - self.start_time
self.prog_bar += '%5ds / %5ds' % (int(elapsed_time),
int(elapsed_time * (100./percentDone-1)))
def update(self, value, every=1, suffix=''):
""" Updates the amount, and writes to stdout. Prints a
carriage return first, so it will overwrite the current
line in stdout."""
if value % every == 0 or value >= self.max:
self.update_amount(newAmount=value, suffix=suffix)
if self.print_msg:
sys.stdout.write('\r' + self.prog_bar)
sys.stdout.flush()
def close(self):
"""Prints a blank space at the end to ensure proper printing
of future statements."""
if self.print_msg:
print(' ')
@@ -0,0 +1,305 @@
#!/usr/bin/env python3
import os,sys,struct,math
import numpy as np
import argparse
from pyint import _utils as ut
import subprocess
#if len(sys.argv) != 5:
# print("Usage:")
# print("./applygacos.py inpfilename ztd1filename ztd2filename elevfilename")
# print(" inpfilenmae : input interferogram, a inpfilename.rsc is needed!")
# print(" ztd1filename: input GACOS ztd day1 filename, a ztd1filename.rsc is needed!")
# print(" ztd2filename: input GACOS ztd day2 filename, a ztd2filename.rsc is needed!")
# print(" elevfilename: elevation angle file, must be the same size with interferogram")
# print(" elevation=90-incidence ")
# print(" can be generated by look_vector in gamma")
# print("outputfile will be saved as inpfilename.gacos")
# print("!!Note, python3 is needed!!")
# exit()
def cmdLineParse():
parser = argparse.ArgumentParser(description='Coregister SM mode SLC to a reference SLC image using GAMMA.',\
formatter_class=argparse.RawTextHelpFormatter,\
epilog=INTRODUCTION+'\n'+EXAMPLE)
parser.add_argument('projectName', help='Name of project.')
parser.add_argument('mdate', help='date of the slave SLC image')
parser.add_argument('sdate', help='date of the slave SLC image')
parser.add_argument('ztd1', help='input GACOS ztd day1 filename, a ztd2filename.rsc is needed!')
parser.add_argument('ztd2', help='input GACOS ztd day2 filename, a ztd2filename.rsc is needed!' )
inps = parser.parse_args()
return inps
INTRODUCTION = '''
-------------------------------------------------------------------
create_files for psokinv software running file by generated by Gamma
'''
EXAMPLE = """Usage:
coreg_gamma.py projectName
coreg_gamma.py PacayaT163TsxHhA
-------------------------------------------------------------------
"""
#filename=sys.argv[1]
#ztd1filename=sys.argv[2]
#ztd2filename=sys.argv[3]
#elevfilename=sys.argv[4]
#print("start processing "+ filename)
class HEADER:
width = 0
length = 0
xfirst = 0.0
yfirst = 0.0
xstep = 0.0
ystep = 0.0
def read_header(filename):
if not os.path.isfile(filename):
print(filename+" file not exit")
header = HEADER()
with open(filename) as f:
for line in f:
data=line.split()
if data[0] == "WIDTH":
header.width=int(data[1])
if data[0] == "FILE_LENGTH":
header.length=int(data[1])
if data[0] == "X_FIRST":
header.xfirst=float(data[1])
if data[0] == "Y_FIRST":
header.yfirst=float(data[1])
if data[0] == "X_STEP":
header.xstep=float(data[1])
if data[0] == "Y_STEP":
header.ystep=float(data[1])
return header
def cut_image2(filename,headername,yfirst_new,length_new,xfirst_new,width_new):
header=read_header(headername)
#print(yfirst_new, header.yfirst)
#print(length_new, header.length)
#print(xfirst_new, header.xfirst)
#print(width_new, header.width)
with open(filename, 'rb') as f:
data0 = np.fromfile(f, dtype=np.float32)
data = np.reshape(data0, (header.length, header.width))
out=np.zeros((length_new,width_new),dtype=np.float32)
#out=np.zeros(width_new*length_new,dtype=np.float32)
for i in range(header.length):
lat=header.yfirst+header.ystep*i
row=int(round((lat-yfirst_new)/header.ystep))
if(row<0 or row>=length_new):
continue
for j in range(header.width):
lon=header.xfirst+header.xstep*j
col=int(round((lon-xfirst_new)/header.xstep))
if(col<0 or col>=width_new):
continue
#out[width_new*row+col]=data[header.width*i+j]
out[row,col]=data[i,j]
out=np.where(out==0,np.nan,out)
#print(np.nanstd(out))
out.tofile(filename+".cut")
f = open(filename+".cut.rsc", 'w')
f.write("WIDTH "+str(width_new)+"\n")
f.write("FILE_LENGTH "+str(length_new)+"\n")
f.write("X_FIRST "+ str(xfirst_new)+"\n")
f.write("Y_FIRST "+ str(yfirst_new)+"\n")
f.write("X_STEP "+ str(header.xstep)+"\n")
f.write("Y_STEP "+ str(header.ystep)+"\n")
f.close()
def make_correction(phsfilename,ztd1filename,ztd2filename,elevfilename):
header=read_header(phsfilename+".rsc")
if not os.path.isfile(ztd1filename+".cut"):
cut_image2(ztd1filename,ztd1filename+".rsc",header.yfirst,header.length,header.xfirst,header.width)
if not os.path.isfile(ztd2filename+".cut"):
cut_image2(ztd2filename,ztd2filename+".rsc",header.yfirst,header.length,header.xfirst,header.width)
with open(phsfilename, 'rb') as f:
data = np.fromfile(f, dtype=np.float32)
phase = np.reshape(data, [header.length, header.width])
with open(ztd1filename+".cut", 'rb') as f:
data = np.fromfile(f, dtype=np.float32)
ztd1 = np.reshape(data, [header.length, header.width])
with open(ztd2filename+".cut", 'rb') as f:
data = np.fromfile(f, dtype=np.float32)
ztd2 = np.reshape(data, [header.length, header.width])
with open(elevfilename, 'rb') as f:
data = np.fromfile(f, dtype=np.float32)
elev = np.reshape(data, [header.length, header.width])
#os.remove(ztd1filename+".cut")
#os.remove(ztd2filename+".cut")
dztd=ztd2-ztd1
dztd=dztd/0.0044138251819503
dztd=dztd/np.sin(elev)
index=np.where(phase==0)
phase[index]=np.nan
phasemean=np.nanmean(phase)
print("before "+str(np.nanstd(phase)))
phase=phase-phasemean
#phase.tofile(phsfilename+".raw")
phase=phase-dztd
phase[index]=np.nan
phasemean=np.nanmean(phase)
print("after "+str(np.nanstd(phase)))
phase=phase-phasemean
phase[index]=0
phase.tofile(phsfilename+".gacos")
def main(argv):
inps = cmdLineParse()
projectName = inps.projectName
Sdate = inps.sdate
Mdate = inps.mdate
scratchDir = os.getenv('SCRATCHDIR')
templateDir = os.getenv('TEMPLATEDIR')
templateFile = templateDir + "/" + projectName + ".template"
templateDict=ut.update_template(templateFile)
rlks = templateDict['range_looks']
azlks = templateDict['azimuth_looks']
Smdate = templateDict['masterDate']
demDir = scratchDir + '/' + projectName + '/DEM'
slcDir = scratchDir + '/' + projectName + "/SLC"
rslcDir = scratchDir + '/' + projectName + "/RSLC"
ifgramDir = scratchDir + '/' + projectName + "/ifgrams"
workDir = ifgramDir + '/' + Mdate + '-' + Sdate
MslcDir = rslcDir + '/' + Mdate
SslcDir = rslcDir + '/' + Sdate
offpar = SslcDir + '/' + Smdate + '_' + Sdate + '.off'
slcpar = MslcDir + '/' + Smdate + '.rslc.par'
dempar = demDir + '/' + Smdate + '_' + rlks + 'rlks.utm.dem.par'
dem = demDir + '/' + Smdate + '_' + rlks + 'rlks.utm.dem'
unwpar = demDir + '/' + Mdate + '_' + rlks + 'rlks.utm.dem.par'
unw = workDir + '/geo_' + Mdate + '-' + Sdate + "_" + rlks+"rlks.diff_filt.unw"
os.chdir(workDir)
call_str = "look_vector " + slcpar+ " " + offpar + " " + dempar + " " + dem + ' lv_theta lv_phi'
os.system(call_str)
call_str = "grep 'corner_lat:' " + dempar + " | awk '{print $2}' "
North=subprocess.getstatusoutput(call_str)[1]
call_str = "grep 'corner_lon:' " + dempar + " | awk '{print $2}' "
West=subprocess.getstatusoutput(call_str)[1]
call_str = "grep 'post_lat:' " + dempar + " | awk '{print $2}' "
posty=subprocess.getstatusoutput(call_str)[1]
call_str = "grep 'post_lon:' " + dempar + " | awk '{print $2}' "
postx=subprocess.getstatusoutput(call_str)[1]
call_str = "grep 'width:' " + dempar + " | awk '{print $2}' "
width=subprocess.getstatusoutput(call_str)[1]
call_str = "grep 'nlines:' " + dempar + " | awk '{print $2}' "
length=subprocess.getstatusoutput(call_str)[1]
South=str(round(float(North)+(float(length)-1)*float(posty),7))
East=str(round(float(West)+(float(width)-1)*float(postx),7))
call_str = "swap_bytes lv_theta lv_theta.phase_swap 4 >dinsar.log "
os.system(call_str)
call_str = "gmt xyz2grd lv_theta.phase_swap -Glv_theta.grd -Ddegree/degree/cm/1/0/=/= -R" + West + "/" + East + "/" +South + "/" +North + " -I" + postx + " -ZTLf -N0"
os.system(call_str)
call_str = "gmt grdmath 90 lv_theta.grd 3.1415926 DIV 180 MUL SUB = lv_theta_final.grd"
os.system(call_str)
call_str = "gmt grdmath 90 lv_theta_final.grd SUB = lv_elev.grd"
os.system(call_str)
call_str = "gmt grdsample lv_elev.grd -Glv_elev_3c.grd -I3c"
os.system(call_str)
call_str = "gmt grd2xyz lv_elev_3c.grd -ZTLf -N0 > " + Mdate + '-' + Sdate + '.gacos.elev'
os.system(call_str)
call_str = "swap_bytes " + unw+ " unw.phase_swap 4 >dinsar.log "
os.system(call_str)
call_str = "gmt xyz2grd unw.phase_swap -Gunw_f.grd -Ddegree/degree/cm/1/0/=/= -R" + West + "/" + East + "/" +South + "/" +North + " -I" + postx +" -ZTLf -N0"
os.system(call_str)
call_str = "gmt grdsample unw_f.grd -Gunw.grd -I3c"
os.system(call_str)
call_str = "gmt grd2xyz unw.grd -ZTLf > " + Mdate + '-' + Sdate + '.gacos.unw'
os.system(call_str)
call_str = "gmt grdinfo unw.grd -C | awk '{print $10}' "
Width=subprocess.getstatusoutput(call_str)[1]
call_str = "gmt grdinfo unw.grd -C | awk '{print $11}' "
line=subprocess.getstatusoutput(call_str)[1]
call_str = "gmt grdinfo unw.grd -C | awk '{print $2}' "
West=subprocess.getstatusoutput(call_str)[1]
call_str = "gmt grdinfo unw.grd -C | awk '{print $5}' "
North=subprocess.getstatusoutput(call_str)[1]
ymax=str(int(round(float(line) ,7)))
xmax=str(int(round(float(Width) ,7)))
output=workDir + '/' + Mdate + '-' + Sdate + '.gacos.unw.rsc'
if os.path.exists(output) is True:
os.remove(output)
fopen=open(output,'a+')
fopen.write('WIDTH ' + Width + '\n')
fopen.write('FILE_LENGTH ' + line + '\n')
fopen.write('XMIN 1' + '\n')
fopen.write('XMAX ' + xmax + '\n')
fopen.write('YMIN 1' + '\n')
fopen.write('YMAX ' + ymax + '\n')
fopen.write('X_FIRST ' + West + '\n')
fopen.write('Y_FIRST ' + North + '\n')
fopen.write('X_STEP 8.33333333E-04' + '\n')
fopen.write('Y_STEP -8.33333333E-04' + '\n')
fopen.write('X_UNIT degrees' + '\n')
fopen.write('Y_UNIT degrees' + '\n')
fopen.write('Z_OFFSET 0' + '\n')
fopen.write('Z_SCALE 1' + '\n')
fopen.write('PROJECTION LATLON' + '\n')
fopen.write('DATUM WGS84' + '\n')
print("convert gamma products to GACOS is done!")
print("start make gacos correction!")
filename=workDir + '/' + Mdate + '-' + Sdate + '.gacos.unw'
ztd1=inps.ztd1
ztd2=inps.ztd2
ztd1filename=workDir + '/' + ztd1
ztd2filename=workDir + '/' + ztd2
elevfilename=workDir + '/' + Mdate + '-' + Sdate + '.gacos.elev'
make_correction(filename,ztd1filename,ztd2filename,elevfilename)
sys.exit(1)
if __name__ == '__main__':
main(sys.argv[:])
#make_correction(filename,ztd1filename,ztd2filename,elevfilename)
#exit()
@@ -0,0 +1,310 @@
#!/usr/bin/env python3
import os,sys,struct,math
import numpy as np
import argparse
from pyint import _utils as ut
import subprocess
#if len(sys.argv) != 5:
# print("Usage:")
# print("./applygacos.py inpfilename ztd1filename ztd2filename elevfilename")
# print(" inpfilenmae : input interferogram, a inpfilename.rsc is needed!")
# print(" ztd1filename: input GACOS ztd day1 filename, a ztd1filename.rsc is needed!")
# print(" ztd2filename: input GACOS ztd day2 filename, a ztd2filename.rsc is needed!")
# print(" elevfilename: elevation angle file, must be the same size with interferogram")
# print(" elevation=90-incidence ")
# print(" can be generated by look_vector in gamma")
# print("outputfile will be saved as inpfilename.gacos")
# print("!!Note, python3 is needed!!")
# exit()
def cmdLineParse():
parser = argparse.ArgumentParser(description='Coregister SM mode SLC to a reference SLC image using GAMMA.',\
formatter_class=argparse.RawTextHelpFormatter,\
epilog=INTRODUCTION+'\n'+EXAMPLE)
parser.add_argument('projectName', help='Name of project.')
parser.add_argument('mdate', help='date of the slave SLC image')
parser.add_argument('sdate', help='date of the slave SLC image')
parser.add_argument('ztd1', help='input GACOS ztd day1 filename, a ztd2filename.rsc is needed!')
parser.add_argument('ztd2', help='input GACOS ztd day2 filename, a ztd2filename.rsc is needed!' )
inps = parser.parse_args()
return inps
INTRODUCTION = '''
-------------------------------------------------------------------
create_files for psokinv software running file by generated by Gamma
'''
EXAMPLE = """Usage:
coreg_gamma.py projectName
coreg_gamma.py PacayaT163TsxHhA
-------------------------------------------------------------------
"""
#filename=sys.argv[1]
#ztd1filename=sys.argv[2]
#ztd2filename=sys.argv[3]
#elevfilename=sys.argv[4]
#print("start processing "+ filename)
class HEADER:
width = 0
length = 0
xfirst = 0.0
yfirst = 0.0
xstep = 0.0
ystep = 0.0
def read_header(filename):
if not os.path.isfile(filename):
print(filename+" file not exit")
header = HEADER()
with open(filename) as f:
for line in f:
data=line.split()
if data[0] == "WIDTH":
header.width=int(data[1])
if data[0] == "FILE_LENGTH":
header.length=int(data[1])
if data[0] == "X_FIRST":
header.xfirst=float(data[1])
if data[0] == "Y_FIRST":
header.yfirst=float(data[1])
if data[0] == "X_STEP":
header.xstep=float(data[1])
if data[0] == "Y_STEP":
header.ystep=float(data[1])
return header
def cut_image2(filename,headername,yfirst_new,length_new,xfirst_new,width_new):
header=read_header(headername)
#print(yfirst_new, header.yfirst)
#print(length_new, header.length)
#print(xfirst_new, header.xfirst)
#print(width_new, header.width)
with open(filename, 'rb') as f:
data0 = np.fromfile(f, dtype=np.float32)
data = np.reshape(data0, (header.length, header.width))
out=np.zeros((length_new,width_new),dtype=np.float32)
#out=np.zeros(width_new*length_new,dtype=np.float32)
for i in range(header.length):
lat=header.yfirst+header.ystep*i
row=int(round((lat-yfirst_new)/header.ystep))
if(row<0 or row>=length_new):
continue
for j in range(header.width):
lon=header.xfirst+header.xstep*j
col=int(round((lon-xfirst_new)/header.xstep))
if(col<0 or col>=width_new):
continue
#out[width_new*row+col]=data[header.width*i+j]
out[row,col]=data[i,j]
out=np.where(out==0,np.nan,out)
#print(np.nanstd(out))
out.tofile(filename+".cut")
f = open(filename+".cut.rsc", 'w')
f.write("WIDTH "+str(width_new)+"\n")
f.write("FILE_LENGTH "+str(length_new)+"\n")
f.write("X_FIRST "+ str(xfirst_new)+"\n")
f.write("Y_FIRST "+ str(yfirst_new)+"\n")
f.write("X_STEP "+ str(header.xstep)+"\n")
f.write("Y_STEP "+ str(header.ystep)+"\n")
f.write("X_UNIT degree"+"\n")
f.write("Y_UNIT degree"+"\n")
f.write("Z_OFFSET 0"+"\n")
f.write("Z_SCALE 1"+"\n")
f.write("PROJECTION LATLON"+"\n")
f.write("DATUM WGS84"+"\n")
f.close()
def make_correction(phsfilename,ztd1filename,ztd2filename,elevfilename):
header=read_header(phsfilename+".rsc")
#if not os.path.isfile(ztd1filename+".cut"):
cut_image2(ztd1filename,ztd1filename+".rsc",header.yfirst,header.length,header.xfirst,header.width)
#if not os.path.isfile(ztd2filename+".cut"):
cut_image2(ztd2filename,ztd2filename+".rsc",header.yfirst,header.length,header.xfirst,header.width)
with open(phsfilename, 'rb') as f:
data = np.fromfile(f, dtype=np.float32)
phase = np.reshape(data, [header.length, header.width])
with open(ztd1filename+".cut", 'rb') as f:
data = np.fromfile(f, dtype=np.float32)
ztd1 = np.reshape(data, [header.length, header.width])
with open(ztd2filename+".cut", 'rb') as f:
data = np.fromfile(f, dtype=np.float32)
ztd2 = np.reshape(data, [header.length, header.width])
with open(elevfilename, 'rb') as f:
data = np.fromfile(f, dtype=np.float32)
elev = np.reshape(data, [header.length, header.width])
#os.remove(ztd1filename+".cut")
#os.remove(ztd2filename+".cut")
dztd=ztd2-ztd1
#dztd=dztd/0.0044138251819503
dztd=dztd/np.sin(elev)
index=np.where(phase==0)
phase[index]=np.nan
phasemean=np.nanmean(phase)
print("before "+str(np.nanstd(phase)))
phase=phase-phasemean
#phase.tofile(phsfilename+".raw")
phase=phase-dztd
phase[index]=np.nan
phasemean=np.nanmean(phase)
print("after "+str(np.nanstd(phase)))
phase=phase-phasemean
phase[index]=0
phase.tofile(phsfilename+".gacos")
def main(argv):
inps = cmdLineParse()
projectName = inps.projectName
Sdate = inps.sdate
Mdate = inps.mdate
scratchDir = os.getenv('SCRATCHDIR')
templateDir = os.getenv('TEMPLATEDIR')
templateFile = templateDir + "/" + projectName + ".template"
templateDict=ut.update_template(templateFile)
rlks = templateDict['range_looks']
azlks = templateDict['azimuth_looks']
Smdate = templateDict['masterDate']
demDir = scratchDir + '/' + projectName + '/DEM'
slcDir = scratchDir + '/' + projectName + "/SLC"
rslcDir = scratchDir + '/' + projectName + "/RSLC"
ifgramDir = scratchDir + '/' + projectName + "/ifgrams"
workDir = ifgramDir + '/' + Mdate + '-' + Sdate
MslcDir = rslcDir + '/' + Mdate
SslcDir = rslcDir + '/' + Sdate
offpar = SslcDir + '/' + Smdate + '_' + Sdate + '.off'
slcpar = MslcDir + '/' + Smdate + '.rslc.par'
dempar = demDir + '/' + Smdate + '_' + rlks + 'rlks.utm.dem.par'
dem = demDir + '/' + Smdate + '_' + rlks + 'rlks.utm.dem'
unwpar = demDir + '/' + Mdate + '_' + rlks + 'rlks.utm.dem.par'
unw = workDir + '/geo_' + Mdate + '-' + Sdate + "_" + rlks+"rlks.diff_filt.unw"
os.chdir(workDir)
call_str = "look_vector " + slcpar+ " " + offpar + " " + dempar + " " + dem + ' lv_theta lv_phi'
os.system(call_str)
call_str = "grep 'corner_lat:' " + dempar + " | awk '{print $2}' "
North=subprocess.getstatusoutput(call_str)[1]
call_str = "grep 'corner_lon:' " + dempar + " | awk '{print $2}' "
West=subprocess.getstatusoutput(call_str)[1]
call_str = "grep 'post_lat:' " + dempar + " | awk '{print $2}' "
posty=subprocess.getstatusoutput(call_str)[1]
call_str = "grep 'post_lon:' " + dempar + " | awk '{print $2}' "
postx=subprocess.getstatusoutput(call_str)[1]
call_str = "grep 'width:' " + dempar + " | awk '{print $2}' "
width=subprocess.getstatusoutput(call_str)[1]
call_str = "grep 'nlines:' " + dempar + " | awk '{print $2}' "
length=subprocess.getstatusoutput(call_str)[1]
South=str(round(float(North)+(float(length)-1)*float(posty),7))
East=str(round(float(West)+(float(width)-1)*float(postx),7))
call_str = "swap_bytes lv_theta lv_theta.phase_swap 4 >dinsar.log "
os.system(call_str)
call_str = "xyz2grd lv_theta.phase_swap -Glv_theta.grd -Ddegree/degree/cm/1/0/=/= -R" + West + "/" + East + "/" +South + "/" +North + " -I" + postx + " -ZTLf -N0"
os.system(call_str)
call_str = "grdmath 90 lv_theta.grd 3.1415926 DIV 180 MUL SUB = lv_theta_final.grd"
os.system(call_str)
call_str = "grdmath 90 lv_theta_final.grd SUB = lv_elev.grd"
os.system(call_str)
call_str = "grdsample lv_elev.grd -Glv_elev_3c.grd -I3c"
# call_str = "grdsample lv_theta_final.grd -Glv_elev_3c.grd -I3c"
os.system(call_str)
call_str = "grd2xyz lv_elev_3c.grd -ZTLf -N0 > " + Mdate + '-' + Sdate + '.gacos.elev'
os.system(call_str)
call_str = "swap_bytes " + unw+ " unw.phase_swap 4 >dinsar.log "
os.system(call_str)
call_str = "xyz2grd unw.phase_swap -Gunw_f.grd -Ddegree/degree/cm/1/0/=/= -R" + West + "/" + East + "/" +South + "/" +North + " -I" + postx +" -ZTLf -N0"
os.system(call_str)
call_str = "grdsample unw_f.grd -Gunw.grd -I3c"
os.system(call_str)
call_str = "grd2xyz unw.grd -ZTLf -N0 > " + Mdate + '-' + Sdate + '.gacos.unw'
os.system(call_str)
call_str = "grdinfo unw.grd -C | awk '{print $10}' "
Width=subprocess.getstatusoutput(call_str)[1]
call_str = "grdinfo unw.grd -C | awk '{print $11}' "
line=subprocess.getstatusoutput(call_str)[1]
call_str = "grdinfo unw.grd -C | awk '{print $2}' "
West=subprocess.getstatusoutput(call_str)[1]
call_str = "grdinfo unw.grd -C | awk '{print $5}' "
North=subprocess.getstatusoutput(call_str)[1]
ymax=str(int(round(float(line) ,7)))
xmax=str(int(round(float(Width) ,7)))
output=workDir + '/' + Mdate + '-' + Sdate + '.gacos.unw.rsc'
if os.path.exists(output) is True:
os.remove(output)
fopen=open(output,'a+')
fopen.write('WIDTH ' + Width + '\n')
fopen.write('FILE_LENGTH ' + line + '\n')
fopen.write('XMIN 1' + '\n')
fopen.write('XMAX ' + xmax + '\n')
fopen.write('YMIN 1' + '\n')
fopen.write('YMAX ' + ymax + '\n')
fopen.write('X_FIRST ' + West + '\n')
fopen.write('Y_FIRST ' + North + '\n')
fopen.write('X_STEP 8.33333333E-04' + '\n')
fopen.write('Y_STEP -8.33333333E-04' + '\n')
fopen.write('X_UNIT degrees' + '\n')
fopen.write('Y_UNIT degrees' + '\n')
fopen.write('Z_OFFSET 0' + '\n')
fopen.write('Z_SCALE 1' + '\n')
fopen.write('PROJECTION LATLON' + '\n')
fopen.write('DATUM WGS84' + '\n')
fopen.close()
print("convert gamma products to GACOS is done!")
print("start make gacos correction!")
filename=workDir + '/' + Mdate + '-' + Sdate + '.gacos.unw'
ztd1=inps.ztd1
ztd2=inps.ztd2
ztd1filename=workDir + '/' + ztd1
ztd2filename=workDir + '/' + ztd2
elevfilename=workDir + '/' + Mdate + '-' + Sdate + '.gacos.elev'
make_correction(filename,ztd1filename,ztd2filename,elevfilename)
sys.exit(1)
if __name__ == '__main__':
main(sys.argv[:])
#make_correction(filename,ztd1filename,ztd2filename,elevfilename)
#exit()
@@ -0,0 +1,105 @@
#! /usr/bin/env python
#################################################################
### This program is part of PyINT v2.1 ###
### Copy Right (c): 2017-2019, Yunmeng Cao ###
### Author: Yunmeng Cao ###
### Contact : ymcmrs@gmail.com ###
#################################################################
import numpy as np
import os
import sys
from PIL import Image
from pylab import *
import argparse
from pyint import _utils as ut
INTRODUCTION = '''
-------------------------------------------------------------------
Unwrap differential interferogram using GAMMA.
[Only support mcf, not implement branch_cut yet]
'''
EXAMPLE = '''
Usage:
unwrap_gamma.py projectName Mdate Sdate
unwrap_gamma.py PacayaT163TsxHhA 20150102 20150601
-------------------------------------------------------------------
'''
def cmdLineParse():
parser = argparse.ArgumentParser(description='Unwrap differential interferogram using GAMMA-mcf method.',\
formatter_class=argparse.RawTextHelpFormatter,\
epilog=INTRODUCTION+'\n'+EXAMPLE)
parser.add_argument('projectName',help='projectName for processing.')
parser.add_argument('Mdate',help='Master date.')
parser.add_argument('Sdate',help='Slave date.')
inps = parser.parse_args()
return inps
def main(argv):
inps = cmdLineParse()
Mdate = inps.Mdate
Sdate = inps.Sdate
projectName = inps.projectName
Sdate = inps.Sdate
Mdate = inps.Mdate
scratchDir = os.getenv('SCRATCHDIR')
templateDir = os.getenv('TEMPLATEDIR')
templateFile = templateDir + "/" + projectName + ".template"
templateDict=ut.update_template(templateFile)
rlks = templateDict['range_looks']
azlks = templateDict['azimuth_looks']
auto_unw = templateDict['auto_unw']
init_flag = templateDict['init_flag']
r_refer = templateDict['r_refer']
a_refer = templateDict['a_refer']
make_mask = templateDict['make_mask']
processDir = scratchDir + '/' + projectName + "/PROCESS"
slcDir = scratchDir + '/' + projectName + "/SLC"
rslcDir = scratchDir + '/' + projectName + '/RSLC'
ifgDir = scratchDir + '/' + projectName + '/ifgrams'
masterDate = templateDict['masterDate']
demDir = scratchDir + '/' + projectName + '/DEM'
Pair = Mdate + '-' + Sdate
workDir = ifgDir + '/' + Pair
################ prepare file for parallel processing ###############
HGTSIM = demDir + '/' + masterDate + '_' + rlks + 'rlks.rdc.dem'
Mamp = workDir + '/' + Mdate + '_' + rlks + 'rlks.amp'
MampPar = workDir + '/' + Mdate + '_' + rlks + 'rlks.amp.par'
Samp = workDir + '/' + Sdate + '_' + rlks + 'rlks.amp'
SampPar = workDir + '/' + Sdate + '_' + rlks + 'rlks.amp.par'
diff_par = workDir + '/' + Mdate + '_' + Sdate + '_diff_par'
UNWlks = workDir + '/' + Pair + '_' +rlks + 'rlks.diff_filt.unw'
CORMASK = workDir + '/' + Pair + '_' +rlks + 'rlks.diff_filt.cor'
ATM_PHASE = workDir + '/' + Pair + '_' +rlks + 'rlks.atm_phae'
ATMCOR_UNW = workDir + '/' + Pair + '_' +rlks + 'rlks.diff_filt.atmcor.unw'
nWidth = ut.read_gamma_par(MampPar, 'read', 'range_samples')
nLine = ut.read_gamma_par(MampPar, 'read', 'azimuth_lines')
###############################################################
call_str = "create_diff_par " + MampPar + " " + SampPar + " " + diff_par + " 1 0 "
os.system(call_str)
call_str = "atm_mod_2d " + UNWlks + " " + HGTSIM + " " + CORMASK + " " + diff_par + " " + " - 0 a0 a1 sigma sigma_h s1"
os.system(call_str)
call_str = "atm_sim_2d " + diff_par + " " + HGTSIM + " a0 a1 " + ATM_PHASE
os.system(call_str)
call_str = "sub_phase " + UNWlks + " " + ATM_PHASE + " " + diff_par + " " + ATMCOR_UNW + " 0 0 0 "
os.system(call_str)
call_str = 'rasrmg ' + ATMCOR_UNW + ' ' + Mamp + ' ' + nWidth + ' - - - - - - - - - - '
os.system(call_str)
print("Correct atmospheric phase is done!")
sys.exit(1)
if __name__ == '__main__':
main(sys.argv[:])
@@ -0,0 +1,121 @@
#! /usr/bin/env python
#################################################################
### This program is part of PyINT v2.1 ###
### Copy Right (c): 2017-2019, Yunmeng Cao ###
### Author: Yunmeng Cao ###
### Contact : ymcmrs@gmail.com ###
#################################################################
import numpy as np
import os
import sys
import getopt
import time
import glob
import argparse
import subprocess
from pyint import _utils as ut
def work(data0):
cmd = data0[0]
err_file = data0[1]
p = subprocess.run(cmd, shell=False,stderr=subprocess.PIPE, stdout=subprocess.PIPE)
stdout = p.stdout
stderr = p.stderr
if type(stderr) == bytes:
aa=stderr.decode("utf-8")
else:
aa = stderr
if aa:
str0 = cmd[0] + ' ' + cmd[1] + ' ' + cmd[2] + ' ' + cmd[3] + '\n'
#print(aa)
with open(err_file, 'a') as f:
f.write(str0)
f.write(aa)
f.write('\n')
return
#########################################################################
INTRODUCTION = '''
-------------------------------------------------------------------
Correct atmospheric phase for one project using GAMMA.
'''
EXAMPLE = '''
Usage:
atm_correction_gamma_all.py projectName
atm_correction_gamma_all.py projectName --parallel 4
atm_correction_gamma_all.py projectName --parallel 4 --ifgramList-txt /test/ifgram_list.txt
-------------------------------------------------------------------
'''
def cmdLineParse():
parser = argparse.ArgumentParser(description='Unwrap differential interferograms for one project using GAMMA.',\
formatter_class=argparse.RawTextHelpFormatter,\
epilog=INTRODUCTION+'\n'+EXAMPLE)
parser.add_argument('projectName',help='projectName for processing.')
parser.add_argument('--parallel', dest='parallelNumb', type=int, default=1, help='Enable parallel processing and Specify the number of processors.')
parser.add_argument('--ifgarmList-txt', dest='ifgarmListTxt', help='provided ifgram_list_txt. default: using ifgram_list.txt under projectName folder.')
inps = parser.parse_args()
return inps
def main(argv):
start_time = time.time()
inps = cmdLineParse()
projectName = inps.projectName
scratchDir = os.getenv('SCRATCHDIR')
templateDir = os.getenv('TEMPLATEDIR')
templateFile = templateDir + "/" + projectName + ".template"
projectDir = scratchDir + '/' + projectName
ifgDir = scratchDir + '/' + projectName + '/ifgrams'
templateDict=ut.update_template(templateFile)
rlks = templateDict['range_looks']
azlks = templateDict['azimuth_looks']
if inps.ifgarmListTxt: ifgramList_txt = inps.ifgarmListTxt
else: ifgramList_txt = scratchDir + '/' + projectName + '/ifgram_list.txt'
ifgList0 = ut.read_txt2array(ifgramList_txt)
# ifgList = ifgList0[:,0]
if len(ifgList0)==3:
ifgList=ifgList0[0]
ifgList=[ifgList]
else:
ifgList=ifgList0[:,0]
err_txt = scratchDir + '/' + projectName + '/unwrap_gamma_all.err'
if os.path.isfile(err_txt): os.remove(err_txt)
data_para = []
for i in range(len(ifgList)):
m0 = ut.yyyymmdd(ifgList[i].split('-')[0])
s0 = ut.yyyymmdd(ifgList[i].split('-')[1])
cmd0 = ['atm_correction_gamma.py',projectName, m0, s0]
unw_file0 = ifgDir + '/' + ifgList[i] + '/' + ifgList[i] + '_' + rlks + 'rlks.diff_filt.atmcor.unw.bmp'
data0 = [cmd0,err_txt]
k00 = 0
if os.path.isfile(unw_file0):
if os.path.getsize(unw_file0) > 0:
k00 = 1
if k00==0:
data_para.append(data0)
ut.parallel_process(data_para, work, n_jobs=inps.parallelNumb, use_kwargs=False)
print("Correct atmospheric phase for project %s is done! " % projectName)
ut.print_process_time(start_time, time.time())
sys.exit(1)
if __name__ == '__main__':
main(sys.argv[:])
@@ -0,0 +1,135 @@
#! /usr/bin/env python
#################################################################
### This program is part of PyINT v1.0 ###
### Copy Right (c): 2017, Yunmeng Cao ###
### Author: Yunmeng Cao ###
### Email : ymcmrs@gmail.com ###
### Univ. : Central South University & University of Miami ###
#################################################################
import numpy as np
import os
import sys
import subprocess
import getopt
import time
import glob
def check_variable_name(path):
s=path.split("/")[0]
if len(s)>0 and s[0]=="$":
p0=os.getenv(s[1:])
path=path.replace(path.split("/")[0],p0)
return path
def read_template(File, delimiter='='):
'''Reads the template file into a python dictionary structure.
Input : string, full path to the template file
Output: dictionary, pysar template content
Example:
tmpl = read_template(KyushuT424F610_640AlosA.template)
tmpl = read_template(R1_54014_ST5_L0_F898.000.pi, ':')
'''
template_dict = {}
for line in open(File):
line = line.strip()
c = [i.strip() for i in line.split(delimiter, 1)] #split on the 1st occurrence of delimiter
if len(c) < 2 or line.startswith('%') or line.startswith('#'):
next #ignore commented lines or those without variables
else:
atrName = c[0]
atrValue = str.replace(c[1],'\n','').split("#")[0].strip()
atrValue = check_variable_name(atrValue)
template_dict[atrName] = atrValue
return template_dict
def is_number(s):
try:
int(s)
return True
except ValueError:
return False
def add_zero(s):
if len(s)==1:
s="000"+s
elif len(s)==2:
s="00"+s
elif len(s)==3:
s="0"+s
return s
def usage():
print('''
******************************************************************************************************
Select interferometry pairs from time series SAR images
usage:
Generate_IfgDir.py ProjectName IFG_List
e.g. Generate_IfgDir.py PacayaT163TsxHhA ifg_list
*******************************************************************************************************
''')
def main(argv):
if len(sys.argv)==2:
if argv[0] in ['-h','--help']: usage(); sys.exit(1)
else:
projectName=sys.argv[1]
projectName=sys.argv[1]
scratchDir = os.getenv('SCRATCHDIR')
templateDir = os.getenv('TEMPLATEDIR')
processDir = scratchDir + '/' + projectName + "/ifgrams"
root_dir=os.getcwd()
os.chdir(processDir)
call_str="find . -name '[0-9]*.unw' -print >unw_file"
os.system(call_str)
file_obj=open('unw_file')
all_lines=file_obj.readlines()
for line in all_lines:
unwdate1=line.split("/")[2]
unwdate2=line.split("/")[1]
unwdate3=line.split("/")[0]
str1=unwdate1.split(".")[0]
str2=unwdate1.split(".")[1]
str3=unwdate1.split(".")[2]
unwdate4=str2 + '_' + str1 + '.' + str3
line1=processDir + '/' + unwdate2+ '/' + unwdate4
line2=processDir + '/'+ unwdate2 + '/' + unwdate1
line2=line2.split('\n')[0]
line1=line1.split('\n')[0]
call_str='mv'+ ' ' + line2 + ' ' + line1
os.system(call_str)
call_str="find . -name '[0-9]*.cor' -print >cor_file"
os.system(call_str)
file_obj=open('cor_file')
all_lines=file_obj.readlines()
for line in all_lines:
cordate1=line.split("/")[2]
cordate2=line.split("/")[1]
cordate3=line.split("/")[0]
str1=cordate1.split(".")[0]
str2=cordate1.split(".")[1]
str3=cordate1.split(".")[2]
sub1=str2.split('_')[1]
cordate4=sub1 + '_' + str1 + '.' + str3
line1=processDir + '/' + cordate2 + '/' + cordate4
line1=line1.split('\n')[0]
line2=processDir + '/'+ cordate2 + '/' + cordate1
line2=line2.split('\n')[0]
call_str='mv' + ' ' + line2 + ' ' + line1
os.system(call_str)
sys.exit(1)
if __name__ == '__main__':
main(sys.argv[:])
@@ -0,0 +1,23 @@
#!/bin/csh -f
if ($#argv != 2) then
echo ""
echo "Usage: read_phs_file.csh phase_file header.rsc"
echo ""
echo "Convert binary files to .grd file"
echo ""
echo "binary file and header in .rsc is needed"
exit 1
endif
#######File to grid#########
set x_first_d1 = `cat $2|grep X_FIRST|awk '{print $2}'`
set y_first_d1 = `cat $2|grep Y_FIRST|awk '{print $2}'`
set width_d1 = `cat $2|grep WIDTH|awk '{print $2}'`
set length_d1 = `cat $2|grep FILE_LENGTH|awk '{print $2}'`
set x_step_d1 = `cat $2|grep X_STEP|awk '{print $2}'`
set y_step_d1 = `cat $2|grep X_STEP|awk '{print $2}'`
set name = `echo $1| awk -F/ '{print $NF}'`
gmt xyz2grd $1 -G"$name.grd" -RLT$x_first_d1/$y_first_d1/$width_d1/$length_d1 -I$x_step_d1/$y_step_d1 -ZTLf -di0 -r
echo "From $1, $name.grd has been produced"
@@ -0,0 +1,242 @@
#! /usr/bin/env python
#################################################################
### This program is part of PyINT v2.1 ###
### Copy Right (c): 2017-2019, Yunmeng Cao ###
### Author: Yunmeng Cao ###
### Contact : ymcmrs@gmail.com ###
#################################################################
import numpy as np
import os
import sys
import argparse
from pyint import _utils as ut
def _run_or_raise(call_str, stage):
rc = os.system(call_str)
if rc != 0:
raise RuntimeError('%s failed with rc=%s: %s' % (stage, rc, call_str))
return rc
def _safe_remove(path):
if path and os.path.exists(path):
os.remove(path)
def _copy_file(src, dst):
ut.copy_file(src, dst)
def cmdLineParse():
parser = argparse.ArgumentParser(description='Coregister SM mode SLC to a reference SLC image using GAMMA.',\
formatter_class=argparse.RawTextHelpFormatter,\
epilog=INTRODUCTION+'\n'+EXAMPLE)
parser.add_argument('projectName', help='Name of project.')
parser.add_argument('sdate', help='date of the slave SLC image. [mater date is read from template]')
inps = parser.parse_args()
return inps
INTRODUCTION = '''
-------------------------------------------------------------------
Coregister SM mode SLC to a reference SLC image using GAMMA.
[The reference date or master date will be read from the template file.]
'''
EXAMPLE = """Usage:
coreg_gamma.py projectName Sdate
coreg_gamma.py PacayaT163TsxHhA 20150102
-------------------------------------------------------------------
"""
def main(argv):
inps = cmdLineParse()
projectName = inps.projectName
Sdate = inps.sdate
scratchDir = os.getenv('SCRATCHDIR')
templateDir = os.getenv('TEMPLATEDIR')
templateFile = templateDir + "/" + projectName + ".template"
slcDir = scratchDir + '/' + projectName + "/SLC"
rslcDir = scratchDir + '/' + projectName + "/RSLC"
if not os.path.isdir(rslcDir): os.mkdir(rslcDir)
#workDir = processDir + '/' + igramDir
workDir = rslcDir + '/' + Sdate
if not os.path.isdir(workDir): os.mkdir(workDir)
templateDict=ut.update_template(templateFile)
rlks = templateDict['range_looks']
azlks = templateDict['azimuth_looks']
Mdate = templateDict['masterDate']
IFGPair = Mdate + '-' + Sdate
demDir = scratchDir + '/' + projectName + '/DEM'
SslcDir = slcDir + '/' + Sdate
Samp = slcDir + '/' + Sdate + '/' + Sdate + '_' + rlks + 'rlks.amp'
SampPar = slcDir + '/' + Sdate + '/' + Sdate + '_' + rlks + 'rlks.amp.par'
Sramp = rslcDir + '/' + Sdate + '/' + Sdate + '_' + rlks + 'rlks.amp'
SrampPar = rslcDir + '/' + Sdate + '/' + Sdate + '_' + rlks + 'rlks.amp.par'
Sslc = slcDir + '/' + Sdate + '/' + Sdate + '.slc'
SslcPar = slcDir + '/' + Sdate + '/' + Sdate + '.slc.par'
SrslcDir = rslcDir + "/" + Sdate
Srslc = SrslcDir + "/" + Sdate + ".rslc"
SrslcPar = SrslcDir + "/" + Sdate + ".rslc.par"
Srslc0 = SrslcDir + "/" + Sdate + ".rslc0"
SrslcPar0 = SrslcDir + "/" + Sdate + ".rslc0.par"
#####################################################
## copy all of the master files into slave folder for parallel processing
remove_file = []
Mslc0 = slcDir + '/' + Mdate + '/' + Mdate + '.slc'
MslcPar0 = slcDir + '/' + Mdate + '/' + Mdate + '.slc.par'
Mamp0 = slcDir + '/' + Mdate + '/' + Mdate + '_' + rlks + 'rlks.amp'
MampPar0 = slcDir + '/' + Mdate + '/' + Mdate + '_' + rlks + 'rlks.amp.par'
Mamp0_dem = demDir + '/' + Mdate + '_' + rlks + 'rlks.amp'
MampPar0_dem = demDir + '/' + Mdate + '_' + rlks + 'rlks.amp.par'
HGTSIM0 = demDir + '/' + Mdate + '_' + rlks + 'rlks.rdc.dem'
if not os.path.isfile(HGTSIM0):
call_str = 'generate_rdc_dem.py ' + projectName
_run_or_raise(call_str, 'generate_rdc_dem')
if not os.path.isfile(Mamp0) and os.path.isfile(Mamp0_dem):
ut.copy_file(Mamp0_dem, Mamp0)
if not os.path.isfile(MampPar0) and os.path.isfile(MampPar0_dem):
ut.copy_file(MampPar0_dem, MampPar0)
if not os.path.isfile(Mamp0) or not os.path.isfile(MampPar0):
call_str = 'multi_look ' + Mslc0 + ' ' + MslcPar0 + ' ' + Mamp0 + ' ' + MampPar0 + ' ' + rlks + ' ' + azlks
_run_or_raise(call_str, 'master_multi_look')
if not os.path.isfile(Samp) or not os.path.isfile(SampPar):
call_str = 'multi_look ' + Sslc + ' ' + SslcPar + ' ' + Samp + ' ' + SampPar + ' ' + rlks + ' ' + azlks
_run_or_raise(call_str, 'slave_multi_look')
Mslc = slcDir + '/' + Sdate + '/' + Mdate + '.slc'
MslcPar = slcDir + '/' + Sdate + '/' + Mdate + '.slc.par'
Mamp = slcDir + '/' + Sdate + '/' + Mdate + '_' + rlks + 'rlks.amp'
MampPar = slcDir + '/' + Sdate + '/' + Mdate + '_' + rlks + 'rlks.amp.par'
HGTSIM = slcDir + '/' + Sdate + '/' + Mdate + '_' + rlks + 'rlks.rdc.dem'
ut.copy_file(HGTSIM0,HGTSIM)
ut.copy_file(Mslc0,Mslc)
ut.copy_file(MslcPar0,MslcPar)
ut.copy_file(Mamp0,Mamp)
ut.copy_file(MampPar0,MampPar)
#######################################################
# define process files #
lt0 = workDir + "/lt0"
lt1 = workDir + "/lt1"
mli0 = workDir + "/mli0"
diff0 = workDir + "/diff0"
offs0 = workDir + "/offs0"
snr0 = workDir + "/snr0"
offsets0 = workDir + "/offsets0"
coffs0 = workDir + "/coffs0"
coffsets0 = workDir + "/coffsets0"
off = workDir + "/" + IFGPair + ".off"
offs = workDir + "/offs"
snr = workDir + "/snr"
offsets = workDir + "/offsets"
coffs = workDir + "/coffs"
coffsets = workDir + "/coffsets"
OFFSTD = workDir + "/" + IFGPair + ".off_std"
##############################################
call_str = "rdc_trans " + MampPar + " " + HGTSIM + " " + SampPar + " " + lt0
_run_or_raise(call_str, 'rdc_trans')
width_Mamp = ut.read_gamma_par(MampPar, 'read', 'range_samples')
width_Samp = ut.read_gamma_par(SampPar, 'read', 'range_samples')
line_Samp = ut.read_gamma_par(SampPar, 'read', 'azimuth_lines')
call_str = "geocode " + lt0 + " " + Mamp + " " + width_Mamp + " " + mli0 + " " + width_Samp + " " + line_Samp + " 2 0"
_run_or_raise(call_str, 'geocode_lt0')
call_str = "create_diff_par " + SampPar + " - " + diff0 + " 1 0"
_run_or_raise(call_str, 'create_diff_par')
try:
call_str = "init_offsetm " + mli0 + " " + Samp + " " + diff0 + " 1 1"
_run_or_raise(call_str, 'init_offsetm')
call_str = "offset_pwrm " + mli0 + " " + Samp + " " + diff0 + " " + offs0 + " " + snr0 + " 256 256 " + offsets0 + " 2 32 32"
_run_or_raise(call_str, 'offset_pwrm')
call_str = "offset_fitm " + offs0 + " " + snr0 + " " + diff0 + " " + coffs0 + " " + coffsets0 + " - 4"
_run_or_raise(call_str, 'offset_fitm')
call_str = "gc_map_fine " + lt0 + " " + width_Mamp + " " + diff0 + " " + lt1
_run_or_raise(call_str, 'gc_map_fine')
except RuntimeError as exc:
print('ERROR: initial DEM-assisted offset refinement failed in strict no-rescue mode')
print(str(exc))
raise
call_str = "SLC_interp_lt " + Sslc + " " + MslcPar + " " + SslcPar + " " + lt1 + " " + MampPar + " " + SampPar + " - " + Srslc0 + " " + SrslcPar0
_run_or_raise(call_str, 'SLC_interp_lt_initial')
############################################ Refinement ############################################
try:
call_str = "create_offset " + MslcPar + " " + SrslcPar0 + " " + off + " 1 - - 0"
_run_or_raise(call_str, 'create_offset')
call_str = "offset_pwr " + Mslc + " " + Srslc0 + " " + MslcPar + " " + SrslcPar0 + " " + off + " " + offs + " " + snr + " " + templateDict['rwin4cor'] + " " + templateDict['azwin4cor'] + " " + offsets + " 2 " + templateDict['rsample4cor'] + " " + templateDict['azsample4cor']
_run_or_raise(call_str, 'offset_pwr_coarse')
call_str = "offset_fit " + offs + " " + snr + " " + off + " " + coffs + " " + coffsets + " - 3"
_run_or_raise(call_str, 'offset_fit_coarse')
rfwin4cor = str(int(1/2*int(templateDict['rwin4cor'])))
azfwin4cor = str(int(1/2*int(templateDict['azwin4cor'])))
rfsample4cor = str(2*int(templateDict['rsample4cor']))
azfsample4cor = str(2*int(templateDict['azsample4cor']))
call_str = "offset_pwr " + Mslc + " " + Srslc0 + " " + MslcPar + " " + SrslcPar0 + " " + off + " " + offs + " " + snr + " " + rfwin4cor + " " + azfwin4cor + " " + offsets + " 2 " + rfsample4cor + " " + azfsample4cor
_run_or_raise(call_str, 'offset_pwr_fine')
call_str = "offset_fit " + offs + " " + snr + " " + off + " " + coffs + " " + coffsets + " - 3 >" + OFFSTD
_run_or_raise(call_str, 'offset_fit_fine')
############################################ Resampling ############################################
call_str = "SLC_interp_lt " + Sslc + " " + MslcPar + " " + SslcPar + " " + lt1 + " " + MampPar + " " + SampPar + " " + off + " " + Srslc + " " + SrslcPar
_run_or_raise(call_str, 'SLC_interp_lt_final')
except RuntimeError as exc:
print('ERROR: offset refinement failed in strict no-rescue mode')
print(str(exc))
raise
call_str = 'multi_look ' + Srslc + ' ' + SrslcPar + ' ' + Sramp + ' ' + SrampPar + ' ' + rlks + ' ' + azlks
_run_or_raise(call_str, 'multi_look_rslc')
nWidth = ut.read_gamma_par(SrampPar, 'read', 'range_samples')
call_str = 'raspwr ' + Sramp + ' ' + nWidth
_run_or_raise(call_str, 'raspwr')
for path in (
lt0, lt1, mli0, diff0, offs0, snr0, offsets0, coffs0, coffsets0,
off, offs, snr, offsets, coffs, coffsets, Srslc0, SrslcPar0,
Mslc, Mamp, HGTSIM,
):
_safe_remove(path)
print("Coregistration with DEM is done!")
sys.exit(0)
if __name__ == '__main__':
main(sys.argv[:])
@@ -0,0 +1,187 @@
#! /usr/bin/env python
#################################################################
### This program is part of PyINT v2.1 ###
### Copy Right (c): 2017-2019, Yunmeng Cao ###
### Author: Yunmeng Cao ###
### Contact : ymcmrs@gmail.com ###
#################################################################
import numpy as np
import os
import sys
import getopt
import time
import glob
import argparse
import shutil
import subprocess
from pyint import _utils as ut
def work(data0):
cmd = data0[0]
err_txt = data0[1]
p = subprocess.run(cmd, shell=False,stderr=subprocess.PIPE, stdout=subprocess.PIPE)
stdout = p.stdout
stderr = p.stderr
if type(stderr) == bytes:
aa=stderr.decode("utf-8")
else:
aa = stderr
if type(stdout) == bytes:
bb=stdout.decode("utf-8", errors="replace")
else:
bb = stdout
if p.returncode != 0:
detail_parts = []
if bb:
detail_parts.append(bb)
if aa:
detail_parts.append(aa)
detail = '\n'.join(part.strip() for part in detail_parts if part and part.strip())
str0 = cmd[0] + ' ' + cmd[1] + ' ' + cmd[2] + '\n'
with open(err_txt, 'a') as f:
f.write(str0)
if detail:
f.write(detail)
f.write('\n')
raise RuntimeError(str0.strip() + ' failed with rc=' + str(p.returncode) + ('\n' + detail if detail else ''))
if aa:
str0 = cmd[0] + ' ' + cmd[1] + ' ' + cmd[2] + '\n'
with open(err_txt, 'a') as f:
f.write(str0)
f.write(aa)
f.write('\n')
return
#########################################################################
def ensure_master_rslc(projectName):
scratchDir = os.getenv('SCRATCHDIR')
templateDir = os.getenv('TEMPLATEDIR')
templateFile = templateDir + "/" + projectName + ".template"
templateDict = ut.update_template(templateFile)
master_date = templateDict['masterDate']
rlks = templateDict['range_looks']
azlks = templateDict['azimuth_looks']
slc_root = scratchDir + '/' + projectName + '/SLC/' + master_date
rslc_root = scratchDir + '/' + projectName + '/RSLC/' + master_date
if not os.path.isdir(rslc_root):
os.makedirs(rslc_root, exist_ok=True)
src_slc = slc_root + '/' + master_date + '.slc'
src_slc_par = slc_root + '/' + master_date + '.slc.par'
src_amp = slc_root + '/' + master_date + '_' + rlks + 'rlks.amp'
src_amp_par = slc_root + '/' + master_date + '_' + rlks + 'rlks.amp.par'
dst_rslc = rslc_root + '/' + master_date + '.rslc'
dst_rslc_par = rslc_root + '/' + master_date + '.rslc.par'
dst_amp = rslc_root + '/' + master_date + '_' + rlks + 'rlks.amp'
dst_amp_par = rslc_root + '/' + master_date + '_' + rlks + 'rlks.amp.par'
if not os.path.isfile(src_slc) or not os.path.isfile(src_slc_par):
raise FileNotFoundError('Master SLC is missing under SLC/' + master_date)
if not os.path.isfile(dst_rslc):
shutil.copyfile(src_slc, dst_rslc)
if not os.path.isfile(dst_rslc_par):
shutil.copyfile(src_slc_par, dst_rslc_par)
if os.path.isfile(src_amp) and not os.path.isfile(dst_amp):
shutil.copyfile(src_amp, dst_amp)
if os.path.isfile(src_amp_par) and not os.path.isfile(dst_amp_par):
shutil.copyfile(src_amp_par, dst_amp_par)
if not os.path.isfile(dst_amp) or not os.path.isfile(dst_amp_par):
cmd = [
'multi_look',
dst_rslc,
dst_rslc_par,
dst_amp,
dst_amp_par,
rlks,
azlks,
]
p = subprocess.run(cmd, shell=False, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
if p.returncode != 0:
detail_parts = []
if p.stdout:
detail_parts.append(p.stdout.decode("utf-8", errors="replace"))
if p.stderr:
detail_parts.append(p.stderr.decode("utf-8", errors="replace"))
detail = '\n'.join(part.strip() for part in detail_parts if part and part.strip())
raise RuntimeError('multi_look master RSLC failed' + ('\n' + detail if detail else ''))
INTRODUCTION = '''
-------------------------------------------------------------------
Coregister all of the SLCs to the reference SAR image using GAMMA.
[with assistant of DEM]
'''
EXAMPLE = '''
Usage:
coreg_gamma_all.py projectName
coreg_gamma_all.py projectName --parallel 4
-------------------------------------------------------------------
'''
def cmdLineParse():
parser = argparse.ArgumentParser(description='Coregister all of the SLCs to the reference SAR image using GAMMA.',\
formatter_class=argparse.RawTextHelpFormatter,\
epilog=INTRODUCTION+'\n'+EXAMPLE)
parser.add_argument('projectName',help='projectName for processing.')
parser.add_argument('--parallel', dest='parallelNumb', type=int, default=1, help='Enable parallel processing and Specify the number of processors.')
inps = parser.parse_args()
return inps
def main(argv):
start_time = time.time()
inps = cmdLineParse()
projectName = inps.projectName
scratchDir = os.getenv('SCRATCHDIR')
templateDir = os.getenv('TEMPLATEDIR')
projectDir = scratchDir + '/' + projectName
slcDir = scratchDir + '/' + projectName + '/SLC'
rslcDir = scratchDir + '/' + projectName + '/RSLC'
if not os.path.isdir(rslcDir): os.mkdir(rslcDir)
ensure_master_rslc(projectName)
if 'S1' in projectName: cmd_command = 'coreg_s1_gamma.py'
else: cmd_command = 'coreg_gamma.py'
err_txt = scratchDir + '/' + projectName + '/coreg_gamma_all.err'
if os.path.isfile(err_txt): os.remove(err_txt)
data_para = []
#slc_list = [os.path.basename(fname) for fname in sorted(glob.glob(slcDir + '/*'))]
master_date = ut.update_template(templateDir + "/" + projectName + ".template")['masterDate']
slc_list = [item for item in ut.get_project_slcList(projectName) if item != master_date]
for i in range(len(slc_list)):
cmd0 = [cmd_command,projectName,slc_list[i]]
data0 = [cmd0,err_txt]
data_para.append(data0)
results = ut.parallel_process(data_para, work, n_jobs=inps.parallelNumb, use_kwargs=False)
failures = [str(item) for item in results if isinstance(item, Exception)]
if failures:
raise RuntimeError('\n\n'.join(failures))
print("Coregister all of the SLCs %s is done! " % projectName)
ut.print_process_time(start_time, time.time())
sys.exit(0)
if __name__ == '__main__':
main(sys.argv[:])
@@ -0,0 +1,239 @@
#! /usr/bin/env python
#################################################################
### This program is part of PyINT v2.1 ###
### Copy Right (c): 2017-2019, Yunmeng Cao ###
### Author: Yunmeng Cao ###
### Contact : ymcmrs@gmail.com ###
#################################################################
import numpy as np
import os
import sys
import argparse
from pyint import _utils as ut
def cmdLineParse():
parser = argparse.ArgumentParser(description='Coregister TOPS S1-SLC to a reference S1-SLC using GAMMA.',\
formatter_class=argparse.RawTextHelpFormatter,\
epilog=INTRODUCTION+'\n'+EXAMPLE)
parser.add_argument('projectName', help='Name of project.')
parser.add_argument('sdate', help='date of the slave S1 image. [mater date is read from template]')
inps = parser.parse_args()
return inps
INTRODUCTION = '''
-------------------------------------------------------------------
Coregister TOPS S1-SLC to a reference S1-SLC using GAMMA.
[The reference date or master date will be read from the template file.]
'''
EXAMPLE = """Usage:
coreg_s1_gamma.py projectName Sdate
coreg_s1_gamma.py PacayaT163TsxHhA 20150102
-------------------------------------------------------------------
"""
def main(argv):
inps = cmdLineParse()
projectName = inps.projectName
Sdate = inps.sdate
scratchDir = os.getenv('SCRATCHDIR')
templateDir = os.getenv('TEMPLATEDIR')
templateFile = templateDir + "/" + projectName + ".template"
slcDir = scratchDir + '/' + projectName + "/SLC"
rslcDir = scratchDir + '/' + projectName + "/RSLC"
if not os.path.isdir(rslcDir): os.mkdir(rslcDir)
#workDir = processDir + '/' + igramDir
workDir = rslcDir + '/' + Sdate
if not os.path.isdir(workDir): os.mkdir(workDir)
templateDict=ut.update_template(templateFile)
rlks = templateDict['range_looks']
azlks = templateDict['azimuth_looks']
Mdate = templateDict['masterDate']
demDir = scratchDir + '/' + projectName + '/DEM'
# Definition of file
MslcDir = slcDir + '/' + Mdate
SslcDir = slcDir + '/' + Sdate
Samp = rslcDir + '/' + Sdate + '/' + Sdate + '_' + rlks + 'rlks.amp'
SampPar = rslcDir + '/' + Sdate + '/' + Sdate + '_' + rlks + 'rlks.amp.par'
Sampbmp = rslcDir + '/' + Sdate + '/' + Sdate + '_' + rlks + 'rlks.amp.bmp'
Mslc = slcDir + '/' + Mdate + '/' + Mdate + '.slc'
Mslcpar = slcDir + '/' + Mdate + '/' + Mdate + '.slc.par'
Mamp = slcDir + '/' + Mdate + '/' + Mdate + '_' + rlks + 'rlks.amp'
MampPar = slcDir + '/' + Mdate + '/' + Mdate + '_' + rlks + 'rlks.amp.par'
Mampbmp = slcDir + '/' + Mdate + '/' + Mdate + '_' + rlks + 'rlks.amp.bmp'
SLC1_INF_tab0 = MslcDir + '/' + Mdate + '_SLC_Tab'
SLC2_INF_tab = SslcDir + '/' + Sdate + '_SLC_Tab'
RSLC_tab = SslcDir + '/' + Sdate + '_RSLC_Tab'
SLC1_INF_tab = SslcDir + '/' + Mdate + '_SLC_Tab_coreg'
HGTSIM = demDir + '/' + Mdate + '_' + rlks + 'rlks.rdc.dem'
if not os.path.isfile(HGTSIM):
call_str = 'generate_rdc_dem.py ' + projectName
os.system(call_str)
############## copy master files into slave folder for parallel process ###########
#if not templateDict['coreg_all_parallel'] == '1':
# Mslc = slcDir + '/' + Sdate + '/' + Mdate + '.slc'
# Mslcpar = slcDir + '/' + Sdate + '/' + Mdate + '.slc.par'
# Mamp = slcDir + '/' + Sdate + '/' + Mdate + '_' + rlks + 'rlks.amp'
# MampPar = slcDir + '/' + Sdate + '/' + Mdate + '_' + rlks + 'rlks.amp.par'
# HGTSIM = slcDir + '/' + Sdate + '/' + Mdate + '_' + rlks + 'rlks.rdc.dem'
#else:
# Mslc = Mslc0
# Mslcpar = Mslcpar0
# Mamp = Mamp0
# MampPar = MampPar0
# HGTSIM = HGTSIM0
#Mslc = slcDir + '/' + Sdate + '/' + Mdate + '.slc'
#Mslcpar = slcDir + '/' + Sdate + '/' + Mdate + '.slc.par'
#Mamp = slcDir + '/' + Sdate + '/' + Mdate + '_' + rlks + 'rlks.amp'
#MampPar = slcDir + '/' + Sdate + '/' + Mdate + '_' + rlks + 'rlks.amp.par'
#HGTSIM = slcDir + '/' + Sdate + '/' + Mdate + '_' + rlks + 'rlks.rdc.dem'
SLC1_INF_tab1 = SslcDir + '/' + Mdate + '_SLC_Tab'
if SslcDir==MslcDir:
SLC1_INF_tab1=SLC1_INF_tab0
else:
ut.copy_file(SLC1_INF_tab0,SLC1_INF_tab1)
##############################################################################
#with open(SLC1_INF_tab1, "r") as f:
# lines = f.readlines()
#with open(SLC1_INF_tab, "w") as fw:
# lines_coreg = []
# for k0 in lines:
# k00 = k0.replace(MslcDir,SslcDir)
# lines_coreg.append(k00)
# fw.write(k00)
S_IW = ut.read_txt2array(SLC1_INF_tab1)
S_IW = S_IW.flatten()
#M_IW = ut.read_txt2array(SLC1_INF_tab1)
#M_IW = M_IW.flatten()
#S_IW = ut.read_txt2array(SLC1_INF_tab)
#S_IW = S_IW.flatten()
#RSLC_tab = workDir + '/' + Sdate + '_RSLC_tab'
#if os.path.isfile(RSLC_tab):
# os.remove(RSLC_tab)
#BURST = SslcDir + '/' + Sdate + '_Burst_Tab'
#AA = np.loadtxt(BURST)
#if EW==SW:
# AA = AA.reshape([1,2])
#
#for kk in range(int(EW)-int(SW)+1):
# ii = int(int(kk) + 1)
# SB2=AA[ii-1,0]
# EB2=AA[ii-1,1]
# call_str = 'echo ' + workDir + '/'+ Sdate+ '_'+ str(int(SB2)) + str(int(EB2)) +'.IW'+str(int(SW)+kk)+ '.rslc' + ' ' + workDir + '/' + Sdate + '_'+ str(int(SB2)) + str(int(EB2)) +'.IW'+ str(int(SW)+kk)+ '.rslc.par' + ' ' + workDir + '/'+ Sdate+'_'+ str(int(SB2)) + str(int(EB2)) + '.IW'+str(int(SW)+kk)+ '.rslc.TOPS_par >>' + RSLC_tab
# os.system(call_str)
os.chdir(workDir)
#TEST = workDir + '/' + Sdate +'_' + rlks + 'rlks.amp.par'
TEST = workDir + '/' + Mdate + '_' + Sdate +'.diff'
k0 = 0
if os.path.isfile(TEST):
if os.path.getsize(TEST) > 0:
k0 = 1
if k0 == 0:
if not Mdate==Sdate:
# call_str = 'S1_coreg_TOPS ' + SLC1_INF_tab1 + ' ' + Mdate + ' ' + SLC2_INF_tab + ' ' + Sdate + ' ' + RSLC_tab + ' ' + HGTSIM + ' ' + rlks + ' ' + azlks + ' - - 0.8 0.01 1.2 1'
call_str = 'ScanSAR_coreg.py ' + SLC1_INF_tab1 + ' ' + Mdate + ' ' + SLC2_INF_tab + ' ' + Sdate + ' ' + RSLC_tab + ' ' + HGTSIM + ' ' + rlks + ' ' + azlks + ' --cc 0.8 --fraction 0.01 --ph_stdev 0.8 --num_ovr 0 --no_check '
print(call_str)
ret = os.system(call_str)
#### clean large file ####
mslc = workDir + '/' + Mdate + '.slc'
mrslc = workDir + '/' + Mdate + '.rslc'
sslc = workDir + '/' + Sdate + '.slc'
srslc = workDir + '/' + Sdate + '.rslc'
srslcPar = workDir + '/' + Sdate + '.rslc.par'
# 检查 ScanSAR_coreg.py 是否成功生成 .rslc(不检查返回码,spectral diversity 步骤可能报错但 RSLC 已生成)
if not os.path.isfile(srslc) or os.path.getsize(srslc) == 0:
print('ERROR: ScanSAR_coreg.py did not produce a valid ' + srslc)
sys.exit(1)
call_str = 'multi_look ' + srslc + ' ' + srslcPar + ' ' + Samp + ' ' + SampPar + ' ' + rlks + ' ' + azlks
os.system(call_str)
nWIDTH = ut.read_gamma_par(SampPar,'read', 'range_samples')
if os.path.isfile(mslc): os.remove(mslc)
if os.path.isfile(mrslc): os.remove(mrslc)
if os.path.isfile(sslc): os.remove(sslc)
call_str = 'raspwr ' + Samp + ' ' + nWIDTH
os.system(call_str)
#call_str = 'rm *mli*'
#os.system(call_str)
#call_str = 'rm *IW*'
#os.system(call_str)
#call_str = 'rm *off*'
#os.system(call_str)
#call_str = 'rm *diff'
#os.system(call_str)
#call_str = 'rm *diff_par*'
#os.system(call_str)
#call_str = 'rm ' + Mdate + '.*'
#os.system(call_str)
else:
call_str = 'cp ' + Mslc + ' ' + workDir + '/' + Mdate + '.rslc'
os.system(call_str)
call_str = 'cp ' + Mslcpar + ' ' + workDir+ '/' + Mdate + '.rslc.par'
os.system(call_str)
call_str = 'cp ' + Mamp + ' ' + workDir+ '/' + Mdate + '_' + rlks + 'rlks.amp'
os.system(call_str)
call_str = 'cp ' + MampPar + ' ' + workDir+ '/' + Mdate + '_' + rlks + 'rlks.amp.par'
os.system(call_str)
ut.copy_file(Mampbmp,Sampbmp)
################ clean redundant files #############
#if not Mdate ==Sdate:
# if not templateDict['diff_all_parallel'] == '1':
# for i in range(len(S_IW)):
# if os.path.isfile(S_IW[i]):
# os.remove(S_IW[i])
# if os.path.isfile(Mslc): os.remove(Mslc)
# if os.path.isfile(Mslcpar): os.remove(Mslcpar)
# if os.path.isfile(Mamp): os.remove(Mamp)
# if os.path.isfile(HGTSIM): os.remove(HGTSIM)
else:
print('The SLC has already coregister Done')
sys.exit(1)
print("Coregister TOP SLC image to the reference TOPS image is done !!")
sys.exit(1)
if __name__ == '__main__':
main(sys.argv[:])

Some files were not shown because too many files have changed in this diff Show More