Skip to content

Commit cc80d5f

Browse files
siwill22claude
andcommitted
Wrap dataset downloads in a diagnostic error, fix more silent failure modes
- Add gprm/datasets/_fetch.py: wraps pooch.retrieve so a failed download raises DatasetFetchError naming the dataset, URL and cache directory, with classified advice for checksum mismatches, HTTP 401/403/404/410/5xx, and connection failures. All dataset loaders now import retrieve from here instead of from pooch directly. - get_merged_cob_terrane_raster() and reconstruct_raster() validate their method/sampling_method arguments up front instead of falling off the end of an if/elif chain into an UnboundLocalError. - ReconstructionModel.to_GPlates() no longer hardcodes a GPlates 2.3.0 path or refuses to run on Linux; it now checks PATH and then globs the usual per-platform install locations, and raises FileNotFoundError with a clear message if none exist. - ReconstructionModel.reconstruct() returns an empty GeoDataFrame (with the input's columns) when nothing reconstructs, instead of printing a message and implicitly returning None. - PointDistributionOnSphere's healpix fallback now catches ImportError specifically rather than a bare except, which previously misreported real errors raised by healpy itself as "unable to import module". - PlateTree.plot_snapshot raises on an unrecognised polygons argument instead of silently doing nothing (was a TODO). - Remove utils.proximity.generate_shadows: dead code with no return statement, and the last user of xrspatial. Drop xarray-spatial from the spatial extra and the stale entry in _optional.py accordingly, since nothing in the codebase imports it any more. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
1 parent a176be8 commit cc80d5f

17 files changed

Lines changed: 294 additions & 44 deletions

‎README.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -45,9 +45,9 @@ which import it at the point of use and tell you what to install if it is missin
4545
GMT >=6 installed separately**: `conda install -c conda-forge gmt`, Homebrew's `gmt`, or
4646
your Linux package manager.
4747
- `pip install "gprm[geophysics]"` — pyshtools, litho1pt0, pmagpy
48-
- `pip install "gprm[spatial]"` — stripy, astropy-healpix, scikit-image, scikit-learn,
49-
xarray-spatial (if astropy-healpix is not installed, some functions fall back on
50-
precomputed point distributions in the `Data` folder)
48+
- `pip install "gprm[spatial]"` — stripy, astropy-healpix, scikit-image, scikit-learn
49+
(if astropy-healpix is not installed, some functions fall back on precomputed point
50+
distributions in the `Data` folder)
5151
- `pip install "gprm[all]"` — everything above
5252

5353
### Where downloaded data goes

‎gprm/GPlatesReconstructionModel.py‎

Lines changed: 51 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -513,11 +513,22 @@ def reconstruct(self, features, reconstruction_time, anchor_plate_id=0,
513513
temporary_file_r.name, reconstruction_time,
514514
anchor_plate_id=anchor_plate_id)
515515

516-
# TODO handle case where there are no reconstructed features, hence file doesn't get created
516+
# pygplates writes no output file when nothing reconstructs, so a read
517+
# failure here means an empty result rather than a real error. Return an
518+
# empty GeoDataFrame with the input's columns, so that callers always get
519+
# the same type back and do not have to test for None.
517520
try:
518521
reconstructed_gdf = gpd.read_file(temporary_file_r.name)
519-
except:
520-
return print('No reconstructed features returned')
522+
except Exception as err:
523+
warnings.warn(
524+
'No features could be reconstructed to {} Ma ({}). Returning an '
525+
'empty GeoDataFrame. Check that the plate ids and valid times of '
526+
'the input features span this reconstruction time.'.format(
527+
reconstruction_time, err))
528+
for _tmp in (temporary_file.name, temporary_file_r.name):
529+
if os.path.exists(_tmp):
530+
os.unlink(_tmp)
531+
return features.iloc[0:0].copy()
521532

522533

523534
# The reconstructed file will have various extra columns, of which the name
@@ -748,23 +759,43 @@ def to_GPlates(self, feature_collections=None, path_to_gplates=None):
748759
'''
749760
Experimental Function to take a list of feature collections and launch
750761
GPlates desktop app with all the features loaded automatically
762+
763+
path_to_gplates: path to the GPlates executable. If not given, the executable is
764+
looked for on PATH and then in the usual install locations for this platform.
751765
'''
752766

753-
import platform, subprocess
767+
import glob, platform, shutil, subprocess
754768

755-
open_gplates_command = []
769+
if path_to_gplates:
770+
if not os.path.exists(path_to_gplates):
771+
raise FileNotFoundError(
772+
'No GPlates executable at {}'.format(path_to_gplates))
773+
else:
774+
# PATH first, so that a user's own install or a conda environment wins over
775+
# whatever happens to be in /Applications.
776+
path_to_gplates = shutil.which('gplates')
756777

757778
if not path_to_gplates:
758-
if platform.system() == 'Darwin':
759-
open_gplates_command.append('/Applications/GPlates_2.3.0/gplates.app/Contents/MacOS/gplates')
779+
# Globbed rather than pinned to a version, so that this does not go stale with
780+
# every GPlates release.
781+
candidate_patterns = {
782+
'Darwin': ['/Applications/GPlates*/gplates.app/Contents/MacOS/gplates',
783+
'/Applications/GPlates*.app/Contents/MacOS/gplates'],
784+
'Linux': ['/usr/bin/gplates', '/usr/local/bin/gplates',
785+
'/opt/gplates*/gplates'],
786+
'Windows': [r'C:\Program Files\GPlates\GPlates*\gplates.exe'],
787+
}.get(platform.system(), [])
788+
789+
candidates = sorted(c for pattern in candidate_patterns for c in glob.glob(pattern))
790+
if candidates:
791+
path_to_gplates = candidates[-1] # highest version, by name
760792

761-
if platform.system() == 'Linux':
762-
raise NotImplementedError()
793+
if not path_to_gplates:
794+
raise FileNotFoundError(
795+
'Could not find a GPlates executable on {}. Put it on PATH, or pass its '
796+
'location as path_to_gplates.'.format(platform.system()))
763797

764-
if platform.system() == 'Windows':
765-
open_gplates_command.append(r'C:\Program Files\GPlates\GPlates 2.3.0\gplates.exe')
766-
else:
767-
open_gplates_command.append(path_to_gplates)
798+
open_gplates_command = [path_to_gplates]
768799

769800
open_gplates_command.extend(self.rotation_files)
770801
open_gplates_command.extend(self.static_polygon_files)
@@ -1516,8 +1547,9 @@ def plot_gmt(self, fig, reconstruction_time, polygons='static',
15161547
elif polygons=='dynamic':
15171548
polygon_type = 'dynamic'
15181549
polygons = self.reconstruction_model.dynamic_polygons
1519-
# TODO else check that the polygons are some other set of polygon features that
1520-
# can be passed to plot_snapshot, else raise error
1550+
else:
1551+
raise ValueError(
1552+
"Unknown polygons {!r}. Choose one of: 'static', 'dynamic'.".format(polygons))
15211553

15221554
links_file = tempfile.NamedTemporaryFile(delete=False, suffix='.xy')
15231555
links_file.close()
@@ -1775,7 +1807,10 @@ def __init__(self, distribution_type='random', N=10000, nest=False):
17751807
# ophis -> longitude, othetas -> latitude
17761808
self.longitude = np.degrees(ophis)
17771809
self.latitude = np.degrees(othetas)
1778-
except:
1810+
except ImportError:
1811+
# Only an absent astropy_healpix should fall back to the bundled meshes. A bare
1812+
# except here also swallowed errors raised *by* healpy (an N that is not a power
1813+
# of two, say) and reported them as an import failure.
17791814
warnings.warn('unable to import module for healpix generation, trying pregenerated point files')
17801815
features = pygplates.FeatureCollection('{:s}/healpix_mesh_{:d}.gpmlz'.format(DATA_DIR,N))
17811816
for feature in features:

‎gprm/datasets/Geology.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
"""
2626

2727
from pooch import os_cache as _os_cache
28-
from pooch import retrieve as _retrieve
28+
from ._fetch import retrieve as _retrieve
2929
from pooch import HTTPDownloader as _HTTPDownloader
3030
from pooch import Unzip as _Unzip
3131
#import pandas as _pd

‎gprm/datasets/Paleogeography.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
"""
2626

2727
from pooch import os_cache as _os_cache
28-
from pooch import retrieve as _retrieve
28+
from ._fetch import retrieve as _retrieve
2929
from pooch import HTTPDownloader as _HTTPDownloader
3030
from pooch import Unzip as _Unzip
3131
#import pandas as _pd

‎gprm/datasets/Reconstructions.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
"""
2626

2727
from pooch import os_cache as _os_cache
28-
from pooch import retrieve as _retrieve
28+
from ._fetch import retrieve as _retrieve
2929
from pooch import HTTPDownloader as _HTTPDownloader
3030
from pooch import Unzip as _Unzip
3131
import pandas as _pd

‎gprm/datasets/Rocks.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
"""
2626

2727
from pooch import os_cache as _os_cache
28-
from pooch import retrieve as _retrieve
28+
from ._fetch import retrieve as _retrieve
2929
from pooch import HTTPDownloader as _HTTPDownloader
3030
from pooch import Unzip as _Unzip
3131
import numpy as _np

‎gprm/datasets/Seafloor.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
"""
2626

2727
from pooch import os_cache as _os_cache
28-
from pooch import retrieve as _retrieve
28+
from ._fetch import retrieve as _retrieve
2929
from pooch import HTTPDownloader as _HTTPDownloader
3030
from pooch import Untar as _Untar
3131
from pooch import Unzip as _Unzip

‎gprm/datasets/Strat.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
"""
2626

2727
from pooch import os_cache as _os_cache
28-
from pooch import retrieve as _retrieve
28+
from ._fetch import retrieve as _retrieve
2929
from pooch import HTTPDownloader as _HTTPDownloader
3030
from pooch import Unzip as _Unzip
3131
import pandas as _pd

‎gprm/datasets/Zircons.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
"""Loaders and analysis tools for detrital zircon U-Pb age datasets."""
22
from pooch import os_cache as _os_cache
3-
from pooch import retrieve as _retrieve
3+
from ._fetch import retrieve as _retrieve
44
from pooch import HTTPDownloader as _HTTPDownloader
55
from pooch import Unzip as _Unzip
66
import pandas as _pd

‎gprm/datasets/__init__.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
'Zircons',
1818
)
1919

20-
__all__ = list(_SUBMODULES) + ['cache_path']
20+
__all__ = list(_SUBMODULES) + ['cache_path', 'DatasetFetchError']
2121

2222

2323
def cache_path(*parts):
@@ -48,6 +48,10 @@ def __getattr__(name):
4848
module = _import_module('.' + name, __name__)
4949
globals()[name] = module # cache, so this runs once per submodule
5050
return module
51+
if name == 'DatasetFetchError':
52+
from ._fetch import DatasetFetchError
53+
globals()[name] = DatasetFetchError
54+
return DatasetFetchError
5155
raise AttributeError("module {!r} has no attribute {!r}".format(__name__, name))
5256

5357

0 commit comments

Comments
 (0)