Skip to content

Commit

Permalink
docs: Harmonized docstrings of all plotting main functions, making th…
Browse files Browse the repository at this point in the history
…em compatible with sphinx docs. Reordered the index of the API reference docs for plotting functions. Also added EvaluationResult and CartesianGrid2D.get_cartesian, which are referenced by the plot docs. Added cartopy for intersphinx_mapping

refac: Renamed plot_spatial_dataset to plot_gridded_dataset (since catalogs are also a spatial datasets)
  • Loading branch information
pabloitu committed Aug 30, 2024
1 parent 7306329 commit 21fcc33
Show file tree
Hide file tree
Showing 8 changed files with 1,297 additions and 1,064 deletions.
6 changes: 3 additions & 3 deletions csep/core/forecasts.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from csep.utils.time_utils import decimal_year, datetime_to_utc_epoch
from csep.core.catalogs import AbstractBaseCatalog
from csep.utils.constants import SECONDS_PER_ASTRONOMICAL_YEAR
from csep.utils.plots import plot_spatial_dataset
from csep.utils.plots import plot_gridded_dataset


# idea: should this be a SpatialDataSet and the class below SpaceMagnitudeDataSet, bc of functions like
Expand Down Expand Up @@ -453,11 +453,11 @@ def plot(self, ax=None, show=False, log=True, extent=None, set_global=False, plo
if log:
plot_args.setdefault('clabel', f'log10 M{self.min_magnitude}+ rate per cell per {time}')
with numpy.errstate(divide='ignore'):
ax = plot_spatial_dataset(numpy.log10(self.spatial_counts(cartesian=True)), self.region, ax=ax,
ax = plot_gridded_dataset(numpy.log10(self.spatial_counts(cartesian=True)), self.region, ax=ax,
show=show, extent=extent, set_global=set_global, plot_args=plot_args)
else:
plot_args.setdefault('clabel', f'M{self.min_magnitude}+ rate per cell per {time}')
ax = plot_spatial_dataset(self.spatial_counts(cartesian=True), self.region, ax=ax,show=show, extent=extent,
ax = plot_gridded_dataset(self.spatial_counts(cartesian=True), self.region, ax=ax, show=show, extent=extent,
set_global=set_global, plot_args=plot_args)
return ax

Expand Down
6 changes: 5 additions & 1 deletion csep/core/regions.py
Original file line number Diff line number Diff line change
Expand Up @@ -674,7 +674,11 @@ def get_cartesian(self, data):
"""Returns 2d ndrray representation of the data set, corresponding to the bounding box.
Args:
data:
data: An array of values, whose indices corresponds to each cell of the region
Returns:
A 2D array of values, corresponding to the original data projected onto the region.
Values outside the region polygon are represented as np.nan
"""
assert len(data) == len(self.polygons)
results = numpy.zeros(self.bbox_mask.shape[:2])
Expand Down
2,240 changes: 1,230 additions & 1,010 deletions csep/utils/plots.py

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,8 @@
"numpy": ("https://docs.scipy.org/doc/numpy/", None),
"pandas": ("http://pandas.pydata.org/pandas-docs/stable/", None),
"scipy": ('http://docs.scipy.org/doc/scipy/reference', None),
"matplotlib": ('http://matplotlib.sourceforge.net/', None)
"matplotlib": ('https://matplotlib.org/stable', None),
"cartopy": ('https://scitools.org.uk/cartopy/docs/latest/', None)
}

html_theme_options = {}
Expand Down
54 changes: 31 additions & 23 deletions docs/reference/api_reference.rst
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,17 @@ Grid-based forecast evaluations:
paired_t_test
w_test

Evaluation result base class

.. automodule:: csep.models

.. autosummary::
:toctree: generated

EvaluationResult


.. currentmodule:: csep.core.regions
.. automodule:: csep.core.regions

Regions
Expand All @@ -191,6 +202,7 @@ Region class(es):
:toctree: generated

CartesianGrid2D
CartesianGrid2D.get_cartesian

Testing regions:

Expand All @@ -199,6 +211,7 @@ Testing regions:

california_relm_region
italy_csep_region
nz_csep_region
global_region

Region utilities:
Expand All @@ -212,55 +225,50 @@ Region utilities:
increase_grid_resolution
masked_region
generate_aftershock_region
california_relm_region

.. currentmodule:: csep.utils.plots
.. automodule:: csep.utils.plots

Plotting
--------

.. automodule:: csep.utils.plots

General plotting:

.. autosummary::
:toctree: generated

plot_histogram
plot_ecdf
plot_magnitude_versus_time
plot_cumulative_events_versus_time
plot_magnitude_histogram
plot_basemap
plot_spatial_dataset
add_labels_for_publication
plot_catalog
plot_gridded_dataset

Plotting from catalogs:
Plotting catalog-based evaluations:

.. autosummary::
:toctree: generated

plot_magnitude_versus_time
plot_catalog
plot_distribution_test
plot_calibration_test

Plotting stochastic event sets and evaluations:
Plotting grid-based evaluations:

.. autosummary::
:toctree: generated

plot_cumulative_events_versus_time
plot_magnitude_histogram
plot_number_test
plot_magnitude_test
plot_distribution_test
plot_likelihood_test
plot_spatial_test
plot_calibration_test
plot_comparison_test
plot_consistency_test

Plotting gridded forecasts and evaluations:
Plotting alarm-based evaluations:

.. autosummary::
:toctree: generated

plot_spatial_dataset
plot_comparison_test
plot_poisson_consistency_test
plot_ROC_diagram
plot_concentration_ROC_diagram
plot_Molchan_diagram


.. automodule:: csep.utils.time_utils

Expand Down
6 changes: 3 additions & 3 deletions examples/tutorials/plot_customizations.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,9 +119,9 @@
# To plot a global forecast, we must assign the option ``set_global=True``, which is required by :ref:cartopy to handle
# internally the extent of the plot

ax = plots.plot_spatial_dataset(numpy.log10(rate_sum), forecast.region,
show=True, set_global=True,
plot_args=plot_args)
ax = plots.plot_gridded_dataset(numpy.log10(rate_sum), forecast.region,
show=True, set_global=True,
plot_args=plot_args)

####################################################################################################################################

Expand Down
4 changes: 2 additions & 2 deletions examples/tutorials/quadtree_gridded_forecast_evaluation.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,9 +192,9 @@


stest_result = [spatial_test_single_res_result, spatial_test_multi_res_result]
ax_spatial = plots.plot_poisson_consistency_test(stest_result,
ax_spatial = plots.plot_consistency_test(stest_result,
plot_args={'xlabel': 'Spatial likelihood'})

ntest_result = [number_test_single_res_result, number_test_multi_res_result]
ax_number = plots.plot_poisson_consistency_test(ntest_result,
ax_number = plots.plot_consistency_test(ntest_result,
plot_args={'xlabel': 'Number of Earthquakes'})
42 changes: 21 additions & 21 deletions tests/test_plots.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,15 @@
)
from csep.utils.plots import (
plot_cumulative_events_versus_time,
plot_magnitude_vs_time,
plot_magnitude_versus_time,
plot_distribution_test,
plot_magnitude_histogram,
plot_calibration_test,
plot_comparison_test,
plot_consistency_test,
plot_basemap,
plot_catalog,
plot_spatial_dataset,
plot_gridded_dataset,
plot_concentration_ROC_diagram,
plot_Molchan_diagram,
plot_ROC_diagram,
Expand Down Expand Up @@ -113,37 +113,37 @@ def setUp(self):

def test_plot_magnitude_vs_time(self):
# Basic test
ax = plot_magnitude_vs_time(catalog=self.observation_m2, show=show_plots)
self.assertEqual(ax.get_title(), "Magnitude vs. Time")
ax = plot_magnitude_versus_time(catalog=self.observation_m2, show=show_plots)
self.assertEqual(ax.get_title(), "")
self.assertEqual(ax.get_xlabel(), "Datetime")
self.assertEqual(ax.get_ylabel(), "$M$")
self.assertEqual(ax.get_ylabel(), "Magnitude")

# Test with custom color
ax = plot_magnitude_vs_time(catalog=self.observation_m2, color="red", show=show_plots)
ax = plot_magnitude_versus_time(catalog=self.observation_m2, color="red", show=show_plots)
scatter_color = ax.collections[0].get_facecolor()[0]
self.assertTrue(all(scatter_color[:3] == (1.0, 0.0, 0.0))) # Check if color is red

# Test with custom marker size
ax = plot_magnitude_vs_time(
ax = plot_magnitude_versus_time(
catalog=self.observation_m2, size=25, max_size=600, show=show_plots
)
scatter_sizes = ax.collections[0].get_sizes()
func_sizes = _autosize_scatter(self.observation_m2.data["magnitude"], 25, 600, 4)
numpy.testing.assert_array_almost_equal(scatter_sizes, func_sizes)

# Test with custom alpha
ax = plot_magnitude_vs_time(catalog=self.observation_m2, alpha=0.5, show=show_plots)
ax = plot_magnitude_versus_time(catalog=self.observation_m2, alpha=0.5, show=show_plots)
scatter_alpha = ax.collections[0].get_alpha()
self.assertEqual(scatter_alpha, 0.5)

# Test with custom marker size power
ax = plot_magnitude_vs_time(catalog=self.observation_m2, power=6, show=show_plots)
ax = plot_magnitude_versus_time(catalog=self.observation_m2, power=6, show=show_plots)
scatter_sizes = ax.collections[0].get_sizes()
func_sizes = _autosize_scatter(self.observation_m2.data["magnitude"], 4, 300, 6)
numpy.testing.assert_array_almost_equal(scatter_sizes, func_sizes)
#
# # Test with show=True (just to ensure no errors occur)
plot_magnitude_vs_time(catalog=self.observation_m2, show=False)
plot_magnitude_versus_time(catalog=self.observation_m2, show=False)
plt.close("all")

def test_plot_cumulative_events_default(self):
Expand Down Expand Up @@ -979,19 +979,19 @@ def tight_bbox():

def test_default_plot(self):
fig, ax = plt.subplots(subplot_kw={"projection": ccrs.PlateCarree()})
ax = plot_spatial_dataset(self.gridded_data, self.region, ax=ax)
ax = plot_gridded_dataset(self.gridded_data, self.region, ax=ax)
self.assertIsInstance(ax, plt.Axes)

def test_extent_setting_w_ax(self):
extent = (-30, 30, -20, 20)
ax = plot_spatial_dataset(
ax = plot_gridded_dataset(
self.gridded_data, self.region, extent=extent, show=show_plots
)
numpy.testing.assert_array_almost_equal(ax.get_extent(crs=ccrs.PlateCarree()), extent)

def test_extent_setting(self):
extent = (-30, 30, -20, 20)
ax = plot_spatial_dataset(
ax = plot_gridded_dataset(
self.gridded_data, self.region, extent=extent, show=show_plots
)
numpy.testing.assert_array_almost_equal(ax.get_extent(crs=ccrs.PlateCarree()), extent)
Expand All @@ -1000,34 +1000,34 @@ def test_extent_setting(self):
def test_color_mapping(self):
cmap = plt.get_cmap("plasma")
fig, ax = plt.subplots(subplot_kw={"projection": ccrs.PlateCarree()})
ax = plot_spatial_dataset(
ax = plot_gridded_dataset(
self.gridded_data, self.region, ax=ax, colormap=cmap, show=show_plots
)
self.assertIsInstance(ax.collections[0].cmap, colors.ListedColormap)

def test_gridlines(self):
fig, ax = plt.subplots(subplot_kw={"projection": ccrs.PlateCarree()})
ax = plot_spatial_dataset(
ax = plot_gridded_dataset(
self.gridded_data, self.region, ax=ax, grid=True, show=show_plots
)
self.assertTrue(ax.gridlines())

def test_alpha_transparency(self):
fig, ax = plt.subplots(subplot_kw={"projection": ccrs.PlateCarree()})
ax = plot_spatial_dataset(
ax = plot_gridded_dataset(
self.gridded_data, self.region, ax=ax, alpha=0.5, show=show_plots
)
self.assertIsInstance(ax, plt.Axes)

def test_plot_with_alpha_exp(self):
ax = plot_spatial_dataset(
ax = plot_gridded_dataset(
self.gridded_data, self.region, alpha_exp=0.5, include_cbar=True, show=show_plots
)
self.assertIsInstance(ax, plt.Axes)

def test_include_colorbar(self):
fig, ax = plt.subplots(subplot_kw={"projection": ccrs.PlateCarree()})
ax = plot_spatial_dataset(
ax = plot_gridded_dataset(
self.gridded_data, self.region, ax=ax, include_cbar=True, show=show_plots
)
colorbars = [
Expand All @@ -1039,7 +1039,7 @@ def test_include_colorbar(self):

def test_no_region_border(self):
fig, ax = plt.subplots(subplot_kw={"projection": ccrs.PlateCarree()})
ax = plot_spatial_dataset(
ax = plot_gridded_dataset(
self.gridded_data, self.region, ax=ax, plot_region=False, show=show_plots
)
lines = ax.get_lines()
Expand All @@ -1048,7 +1048,7 @@ def test_no_region_border(self):
def test_plot_spatial_dataset_w_basemap_stream_kwargs(self):

projection = ccrs.Mercator()
ax = plot_spatial_dataset(
ax = plot_gridded_dataset(
self.gridded_data,
self.region,
extent=[-20, 40, -5, 25],
Expand All @@ -1067,7 +1067,7 @@ def test_plot_spatial_dataset_w_basemap_stream_kwargs(self):

def test_plot_spatial_dataset_w_approx_projection(self):
projection = "approx"
ax = plot_spatial_dataset(
ax = plot_gridded_dataset(
self.gridded_data,
self.region,
basemap="stock_img",
Expand Down

0 comments on commit 21fcc33

Please sign in to comment.