Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Gracefully handle missing files #31

Merged
merged 5 commits into from
Jul 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 19 additions & 27 deletions asp_plot/bundle_adjust.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,22 @@
import os
import glob
import logging
import pandas as pd
import geopandas as gpd
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import contextily as ctx
from asp_plot.utils import ColorBar, Plotter, save_figure
from asp_plot.utils import ColorBar, Plotter, save_figure, glob_file


logging.basicConfig(level=logging.WARNING)
logger = logging.getLogger(__name__)


class ReadBundleAdjustFiles:
def __init__(self, directory, bundle_adjust_directory):
self.directory = directory
self.bundle_adjust_directory = bundle_adjust_directory
self.full_directory = os.path.join(directory, bundle_adjust_directory)

def get_csv_paths(self, geodiff_files=False):
filenames = [
Expand All @@ -22,14 +27,13 @@ def get_csv_paths(self, geodiff_files=False):
if geodiff_files:
filenames = [f.replace(".csv", "-diff.csv") for f in filenames]

paths = [
glob.glob(os.path.join(self.directory, self.bundle_adjust_directory, f))[0]
for f in filenames
]
paths = [glob_file(self.full_directory, f) for f in filenames]

for path in paths:
if not os.path.isfile(path):
raise ValueError(f"CSV file not found: {path}")
if path is None:
raise ValueError(
"\n\nInitial and final bundle adjust CSV file not found. Did you run bundle_adjust?\n\n"
)

initial, final = paths
return initial, final
Expand Down Expand Up @@ -101,15 +105,9 @@ def get_initial_final_geodiff_gdfs(self):
return geodiff_initial_gdf, geodiff_final_gdf

def get_mapproj_residuals_gdf(self):
path = glob.glob(
os.path.join(
self.directory,
self.bundle_adjust_directory,
"*-mapproj_match_offsets.txt",
)
)[0]
if not os.path.isfile(path):
raise ValueError(f"MapProj Residuals TXT file not found: {path}")
path = glob_file(self.full_directory, "*-mapproj_match_offsets.txt")
if path is None:
raise ValueError("\n\nMapProj Residuals TXT file not found.\n\n")

cols = ["lon", "lat", "height_above_datum", "mapproj_ip_dist_meters"]
resid_mapprojected_df = pd.read_csv(path, skiprows=2, names=cols)
Expand All @@ -124,15 +122,9 @@ def get_mapproj_residuals_gdf(self):
return resid_mapprojected_gdf

def get_propagated_triangulation_uncert_df(self):
path = glob.glob(
os.path.join(
self.directory,
self.bundle_adjust_directory,
"*-triangulation_uncertainty.txt",
)
)[0]
if not os.path.isfile(path):
raise ValueError(f"Triangulation Uncertainty TXT file not found: {path}")
path = glob_file(self.full_directory, "*-triangulation_uncertainty.txt")
if path is None:
raise ValueError("\n\nTriangulation Uncertainty TXT file not found.\n\n")

cols = [
"left_image",
Expand All @@ -155,7 +147,7 @@ class PlotBundleAdjustFiles(Plotter):
def __init__(self, geodataframes, **kwargs):
super().__init__(**kwargs)
if not isinstance(geodataframes, list):
raise ValueError("Input must be a list of GeoDataFrames")
raise ValueError("\n\nInput must be a list of GeoDataFrames\n\n")
self.geodataframes = geodataframes

def gdf_percentile_stats(self, gdf, column_name="mean_residual"):
Expand Down
24 changes: 10 additions & 14 deletions asp_plot/processing_parameters.py
Original file line number Diff line number Diff line change
@@ -1,31 +1,27 @@
import os
import glob
import logging
import matplotlib.pyplot as plt
from asp_plot.utils import save_figure
from asp_plot.utils import save_figure, glob_file

logging.basicConfig(level=logging.WARNING)
logger = logging.getLogger(__name__)

class ProcessingParameters:
def __init__(self, directory, bundle_adjust_directory, stereo_directory):
self.directory = directory
self.bundle_adjust_directory = bundle_adjust_directory
self.stereo_directory = stereo_directory
self.full_ba_directory = os.path.join(directory, bundle_adjust_directory)
self.full_stereo_directory = os.path.join(directory, stereo_directory)
self.processing_parameters_dict = {}

try:
self.bundle_adjust_log = glob.glob(
os.path.join(self.directory, self.bundle_adjust_directory, "*log*.txt")
)[0]
self.stereo_log = glob.glob(
os.path.join(self.directory, self.stereo_directory, "*log-stereo*.txt")
)[0]
self.point2dem_log = glob.glob(
os.path.join(
self.directory, self.stereo_directory, "*log-point2dem*.txt"
)
)[0]
self.bundle_adjust_log = glob_file(self.full_ba_directory, "*log-bundle_adjust*.txt")
self.stereo_log = glob_file(self.full_stereo_directory, "*log-stereo*.txt")
self.point2dem_log = glob_file(self.full_stereo_directory, "*log-point2dem*.txt")
except:
raise ValueError(
"Could not find log files in bundle adjust and stereo directories\nCheck that these *log*.txt files exist in the directories specified"
"\n\nCould not find log files in bundle adjust and stereo directories\nCheck that these *log*.txt files exist in the directories specified.\n\n"
)

def from_log_files(self):
Expand Down
64 changes: 40 additions & 24 deletions asp_plot/scenes.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
import os
import glob
import logging
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from shapely import wkt
from asp_plot.utils import Raster, Plotter, save_figure
from asp_plot.utils import Raster, Plotter, save_figure, glob_file
from asp_plot.stereopair_metadata_parser import StereopairMetadataParser


logging.basicConfig(level=logging.WARNING)
logger = logging.getLogger(__name__)


class SceneGeometryPlotter(StereopairMetadataParser):
def __init__(self, directory, **kwargs):
super().__init__(directory=directory, **kwargs)
Expand Down Expand Up @@ -138,7 +142,7 @@ def dg_geom_plot(self, save_dir=None, fig_fn=None):

# TODO: Should store xml names in the pairdict
# Use r100 outputs from dg_mosaic
xml_list = sorted(glob.glob(os.path.join(self.directory, "*r100.[Xx][Mm][Ll]")))
xml_list = sorted(glob_file(self.directory, "*r100.[Xx][Mm][Ll]", all_files=True))

eph1_gdf, eph2_gdf = [self.getEphem_gdf(xml) for xml in xml_list]
fp1_gdf, fp2_gdf = [self.xml2gdf(xml) for xml in xml_list]
Expand Down Expand Up @@ -179,18 +183,10 @@ def __init__(self, directory, stereo_directory, **kwargs):
super().__init__(**kwargs)
self.directory = directory
self.stereo_directory = stereo_directory
self.full_stereo_directory = os.path.join(directory, stereo_directory)

try:
self.left_ortho_sub_fn = glob.glob(
os.path.join(self.directory, self.stereo_directory, "*-L_sub.tif")
)[0]
self.right_ortho_sub_fn = glob.glob(
os.path.join(self.directory, self.stereo_directory, "*-R_sub.tif")
)[0]
except:
raise ValueError(
"Could not find L-sub and R-sub images in stereo directory"
)
self.left_ortho_sub_fn = glob_file(self.full_stereo_directory, "*-L_sub.tif")
self.right_ortho_sub_fn = glob_file(self.full_stereo_directory, "*-R_sub.tif")

def plot_orthos(self, save_dir=None, fig_fn=None):
p = StereopairMetadataParser(self.directory).get_pair_dict()
Expand All @@ -199,17 +195,37 @@ def plot_orthos(self, save_dir=None, fig_fn=None):
fig.suptitle(self.title, size=10)
axa = axa.ravel()

ortho_ma = Raster(self.left_ortho_sub_fn).read_array()
self.plot_array(ax=axa[0], array=ortho_ma, cmap="gray", add_cbar=False)
axa[0].set_title(
f"Left image\n{p['id1_dict']['id']}, {p['id1_dict']['meanproductgsd']:0.2f} m"
)
if self.left_ortho_sub_fn:
ortho_ma = Raster(self.left_ortho_sub_fn).read_array()
self.plot_array(ax=axa[0], array=ortho_ma, cmap="gray", add_cbar=False)
axa[0].set_title(
f"Left image\n{p['id1_dict']['id']}, {p['id1_dict']['meanproductgsd']:0.2f} m"
)
else:
axa[0].text(
0.5,
0.5,
"One or more required\nfiles are missing",
horizontalalignment="center",
verticalalignment="center",
transform=axa[0].transAxes,
)

ortho_ma = Raster(self.right_ortho_sub_fn).read_array()
self.plot_array(ax=axa[1], array=ortho_ma, cmap="gray", add_cbar=False)
axa[1].set_title(
f"Right image\n{p['id2_dict']['id']}, {p['id2_dict']['meanproductgsd']:0.2f} m"
)
if self.right_ortho_sub_fn:
ortho_ma = Raster(self.right_ortho_sub_fn).read_array()
self.plot_array(ax=axa[1], array=ortho_ma, cmap="gray", add_cbar=False)
axa[1].set_title(
f"Right image\n{p['id2_dict']['id']}, {p['id2_dict']['meanproductgsd']:0.2f} m"
)
else:
axa[1].text(
0.5,
0.5,
"One or more required\nfiles are missing",
horizontalalignment="center",
verticalalignment="center",
transform=axa[1].transAxes,
)

fig.tight_layout()
if save_dir and fig_fn:
Expand Down
Loading