lucas-mega / src /process /processor.py
Kuangdai
Initial release of LUCAS-MEGA
9bc98d9
import json
from pathlib import Path
import geopandas as gpd
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import rasterio
from dbfread import DBF
from matplotlib.colors import Normalize
from osgeo import gdal
from rasterio.features import rasterize
from rasterio.transform import from_bounds
def process_tif(input_path: Path, move_list: list[Path] = None, nodata: float = None) -> list[Path]:
"""
Process a single TIFF file by standardising and generating a PNG preview.
Args:
input_path (Path): Path to the TIFF file.
move_list (list[Path], optional): List to append generated files to.
nodata (float, optional): Overwriting nodata value.
Returns:
list[Path]: Updated list of processed files.
"""
if move_list is None:
move_list = []
new_move_list = move_list[:]
if input_path.suffix.lower() not in [".tif", ".tiff", ".asc"] or input_path.is_dir():
print(f"⚠️ Skipped non-TIFF file: {input_path}")
return new_move_list
try:
with rasterio.open(input_path) as src:
data = src.read(1) # preserve original dtype
if nodata is None:
nodata = src.nodata if src.nodata is not None else src.meta.get("nodata")
# Save standardized compressed TIFF
standardized_path = input_path.with_name(input_path.stem + ".standardized.tif")
with rasterio.open(standardized_path, "w", **src.meta, compress="deflate") as dst:
dst.write(data, 1)
new_move_list.append(standardized_path)
# Save PNG preview
step = max(1, int(max(data.shape) / 1000))
data_vis = data[::step, ::step]
if nodata is not None:
mask = np.isclose(data_vis, nodata)
data_vis = np.where(mask, np.nan, data_vis)
norm = Normalize(
vmin=np.nanpercentile(data_vis, 2),
vmax=np.nanpercentile(data_vis, 98)
)
scaled = np.uint8(np.clip(norm(data_vis) * 255, 0, 255))
rgb = np.stack([scaled] * 3, axis=-1)
rgb[np.isnan(data_vis)] = [255, 0, 255]
png_path = input_path.with_suffix(".png")
plt.imsave(png_path, rgb)
new_move_list.append(png_path)
print(f"✅ Processed {input_path.name}")
except Exception as e:
print(f"❌ Failed to process {input_path.name}: {e}")
return new_move_list
def process_excel(input_path: Path, skip_rows=0, move_list: list[Path] = None) -> list[Path]:
"""
Convert Excel file to CSV, skipping header rows automatically if requested.
Args:
input_path (Path): Path to the Excel file.
skip_rows (int or 'auto'): Number of rows to skip before header, or 'auto' to detect.
move_list (list[Path], optional): List to append output CSV to.
Returns:
list[Path]: Updated list of processed files.
"""
if move_list is None:
move_list = []
new_move_list = move_list[:]
if input_path.suffix.lower() not in [".xls", ".xlsx"]:
print(f"⚠️ Skipped non-Excel file: {input_path.name}")
return new_move_list
try:
# Auto-detect header if needed
if skip_rows == "auto":
peek = pd.read_excel(input_path, nrows=5, header=None)
skip_rows = 0
for _, row in peek.iterrows():
if all(isinstance(cell, str) for cell in row if pd.notna(cell)):
break
skip_rows += 1
# Convert Excel to CSV
df = pd.read_excel(input_path, skiprows=skip_rows)
df.columns = df.columns.str.replace(r'[\r\n]+', ' ', regex=True).str.strip()
csv_path = input_path.with_name(input_path.stem + ".csv")
df.to_csv(csv_path, index=False)
new_move_list.append(csv_path)
print(f"✅ Converted Excel to CSV: {csv_path.name}")
except Exception as e:
print(f"❌ Failed to process {input_path.name}: {e}")
return new_move_list
def process_dbf(input_path: Path, move_list: list[Path] = None) -> list[Path]:
"""
Convert DBF file to CSV.
Args:
input_path (Path): Path to the DBF file.
move_list (list[Path], optional): List to append output CSV to.
Returns:
list[Path]: Updated list of processed files.
"""
if move_list is None:
move_list = []
new_move_list = move_list[:]
if input_path.suffix.lower() != ".dbf":
print(f"⚠️ Skipped non-DBF file: {input_path.name}")
return new_move_list
try:
# Read DBF file
df = pd.DataFrame(iter(DBF(input_path)))
# Clean column names
df.columns = df.columns.str.replace(r'[\r\n]+', ' ', regex=True).str.strip()
# Save as CSV
csv_path = input_path.with_name(input_path.stem + ".csv")
df.to_csv(csv_path, index=False)
new_move_list.append(csv_path)
print(f"✅ Converted DBF to CSV: {csv_path.name}")
except Exception as e:
print(f"❌ Failed to process {input_path.name}: {e}")
return new_move_list
def process_shp(input_path: Path, move_list: list[Path] = None,
drop_geometry=False) -> list[Path]:
"""
Process a single Shapefile by extracting the attribute table and saving a meta.
Args:
input_path (Path): Path to the Shapefile (.shp).
move_list (list[Path], optional): List to append output files to.
drop_geometry (bool, optional): Whether to drop geometry columns.
Returns:
list[Path]: Updated list of processed files.
"""
if move_list is None:
move_list = []
new_move_list = move_list[:]
if input_path.suffix.lower() != ".shp":
print(f"⚠️ Skipped non-Shapefile: {input_path.name}")
return new_move_list
try:
# Read the shapefile
gdf = gpd.read_file(input_path)
# Save attribute table (drop geometry)
df = gdf.drop(columns=gdf.geometry.name, errors='ignore') if drop_geometry else gdf
csv_path = input_path.with_name(input_path.stem + ".shp.csv")
df.to_csv(csv_path, index=False)
new_move_list.append(csv_path)
# Save basic meta as JSON
meta = {
"n_features": len(gdf),
"crs": str(gdf.crs),
"bounds": gdf.total_bounds.tolist(), # [minx, miny, maxx, maxy]
"fields": list(df.columns)
}
json_path = input_path.with_name(input_path.stem + ".meta.json")
with open(json_path, "w") as f:
json.dump(meta, f, indent=2)
new_move_list.append(json_path)
print(f"✅ Processed Shapefile: {input_path.name}")
except Exception as e:
print(f"❌ Failed to process {input_path.name}: {e}")
return new_move_list
def process_rdc_rst(rdc_path: Path, move_list: list[Path] = None, nodata: float = None) -> list[Path]:
"""
Process an RDC/RST pair by standardising and generating a PNG preview.
Args:
rdc_path (Path): Path to the RDC file.
move_list (list[Path], optional): List to append generated files to.
nodata (float, optional): Overwriting nodata value.
Returns:
list[Path]: Updated list of processed files.
"""
if move_list is None:
move_list = []
new_move_list = move_list[:]
if rdc_path.suffix.lower() != ".rdc":
print(f"⚠️ Skipped non-RDC file: {rdc_path}")
return new_move_list
# Parse RDC metadata
try:
with open(rdc_path, "r") as f:
lines = f.readlines()
meta_dict = {}
for line in lines:
if ":" in line:
key, value = line.split(":", 1)
meta_dict[key.strip().lower()] = value.strip()
cols = int(meta_dict["columns"])
rows = int(meta_dict["rows"])
min_x = float(meta_dict["min. x"])
max_y = float(meta_dict["max. y"])
if nodata is None:
nodata_str = meta_dict.get("flag value", "none")
nodata = None if nodata_str.lower() == "none" else float(nodata_str)
# Resolution handling
try:
res = float(meta_dict["resolution"])
except ValueError:
# Compute resolution from extents
res_x = (float(meta_dict["max. x"]) - float(meta_dict["min. x"])) / cols
res_y = (float(meta_dict["max. y"]) - float(meta_dict["min. y"])) / rows
if not np.isclose(res_x, res_y):
print(f"⚠️ WARNING: non-square pixel! res_x={res_x}, res_y={res_y}")
res = res_x # or res_y — assume square pixels
# Define geotransform: (min_x, res, 0, max_y, 0, -res)
geotransform = (min_x, res, 0, max_y, 0, -res)
except Exception as e:
print(f"❌ Failed to parse RDC: {rdc_path.name}: {e}")
return new_move_list
# Read RST with GDAL
try:
rst_path = rdc_path.with_suffix(".rst")
ds = gdal.Open(str(rst_path))
band = ds.GetRasterBand(1)
data = band.ReadAsArray()
# Apply nodata mask
if nodata is not None:
data = np.ma.masked_equal(data, nodata)
# Save standardized compressed TIFF
standardized_path = rdc_path.with_name(rdc_path.stem + ".standardized.tif")
driver = gdal.GetDriverByName("GTiff")
out_ds = driver.Create(
str(standardized_path), cols, rows, 1, gdal.GDT_Float32, options=["COMPRESS=DEFLATE"]
)
out_ds.SetGeoTransform(geotransform)
out_ds.SetProjection("") # No CRS info in RDC, can leave empty or set if known
out_band = out_ds.GetRasterBand(1)
out_band.WriteArray(data)
if nodata is not None:
out_band.SetNoDataValue(nodata)
out_ds.FlushCache()
new_move_list.append(standardized_path)
# Save PNG preview
step = max(1, int(max(data.shape) / 1000))
data_vis = data[::step, ::step]
if nodata is not None:
mask = np.isclose(data_vis, nodata)
data_vis = np.where(mask, np.nan, data_vis)
norm = Normalize(
vmin=np.nanpercentile(data_vis, 2),
vmax=np.nanpercentile(data_vis, 98)
)
scaled = np.uint8(np.clip(norm(data_vis) * 255, 0, 255))
rgb = np.stack([scaled] * 3, axis=-1)
rgb[np.isnan(data_vis)] = [255, 0, 255]
png_path = rdc_path.with_suffix(".png")
plt.imsave(png_path, rgb)
new_move_list.append(png_path)
print(f"✅ Processed RDC/RST pair: {rdc_path.name}")
except Exception as e:
print(f"❌ Failed to process RDC/RST pair: {rdc_path.name}: {e}")
return new_move_list
def rasterize_shp(shp_path, columns, resolution_m=1000, out_dir=None, crs="EPSG:3035"):
"""
Rasterize specified columns from a shapefile into GeoTIFF rasters.
Parameters
----------
shp_path : str or Path
Path to the shapefile (.shp).
columns : list of str
List of column names in the shapefile to rasterize.
resolution_m : float, optional
Pixel size in meters (default = 1000, i.e. 1 km resolution).
out_dir : str or Path, optional
Output directory for GeoTIFFs. If None, same directory as shapefile.
crs : str or int, optional
Target coordinate reference system (default = 'EPSG:3035').
Output
------
Saves GeoTIFFs named '<shapefile_stem>__<column>.tif' in the output directory.
"""
shp_path = Path(shp_path)
out_dir = Path(out_dir) if out_dir else shp_path.parent
out_dir.mkdir(parents=True, exist_ok=True)
gdf = gpd.read_file(shp_path)
gdf = gdf.to_crs(crs)
missing_cols = [c for c in columns if c not in gdf.columns]
if missing_cols:
raise ValueError(f"Missing columns in shapefile: {missing_cols}")
minx, miny, maxx, maxy = gdf.total_bounds
width = int((maxx - minx) / resolution_m)
height = int((maxy - miny) / resolution_m)
transform = from_bounds(minx, miny, maxx, maxy, width, height)
stem = shp_path.stem
for col in columns:
print(f"Rasterizing '{col}' ...")
shapes = ((geom, val) for geom, val in zip(gdf.geometry, gdf[col]))
out_path = out_dir / f"{stem}__{col}.tif"
with rasterio.open(
out_path,
"w",
driver="GTiff",
height=height,
width=width,
count=1,
dtype="float32",
crs=gdf.crs,
transform=transform,
nodata=-9999,
) as dst:
raster = rasterize(
shapes=shapes,
out_shape=(height, width),
transform=transform,
fill=-9999,
dtype="float32",
)
dst.write(raster, 1)
print(f"✅ Saved → {out_path}")
print("🎉 Rasterization complete.")