From 7dfc8218ed71d026e1f3f225a3e364b347e59b84 Mon Sep 17 00:00:00 2001 From: mcflugen Date: Fri, 20 Dec 2024 11:56:04 -0700 Subject: [PATCH 1/4] apply black to deltametrics docstrings --- deltametrics/cube.py | 15 +- deltametrics/mask.py | 119 +++++++--------- deltametrics/mobility.py | 35 +++-- deltametrics/plan.py | 152 ++++++++++---------- deltametrics/plot.py | 89 ++++++------ deltametrics/sample_data/sample_data.py | 8 ++ deltametrics/section.py | 177 ++++++++++++------------ deltametrics/strat.py | 67 +++++---- deltametrics/utils.py | 6 +- 9 files changed, 329 insertions(+), 339 deletions(-) diff --git a/deltametrics/cube.py b/deltametrics/cube.py index a172a525..f9dfcd39 100644 --- a/deltametrics/cube.py +++ b/deltametrics/cube.py @@ -452,11 +452,10 @@ def quick_show(self, var, idx=-1, axis=0, **kwargs): >>> from deltametrics.sample_data.sample_data import golf >>> golfcube = golf() - >>> golfstrat = StratigraphyCube.from_DataCube( - ... golfcube, dz=0.1) + >>> golfstrat = StratigraphyCube.from_DataCube(golfcube, dz=0.1) >>> fig, ax = plt.subplots(2, 1) - >>> golfcube.quick_show('eta', ax=ax[0]) # a Planform (axis=0) - >>> golfstrat.quick_show('eta', idx=100, axis=2, ax=ax[1]) # a DipSection + >>> golfcube.quick_show("eta", ax=ax[0]) # a Planform (axis=0) + >>> golfstrat.quick_show("eta", idx=100, axis=2, ax=ax[1]) # a DipSection """ if axis == 0: # this is a planform slice @@ -509,15 +508,13 @@ def show_cube(self, var, style="mesh", ve=200, ax=None): >>> from deltametrics.sample_data.sample_data import golf >>> golfcube = golf() - >>> golfstrat = StratigraphyCube.from_DataCube( - ... golfcube, dz=0.1) - ... + >>> golfstrat = StratigraphyCube.from_DataCube(golfcube, dz=0.1) >>> fig, ax = plt.subplots() - >>> golfstrat.show_cube('eta', ax=ax) # doctest: +SKIP + >>> golfstrat.show_cube("eta", ax=ax) # doctest: +SKIP >>> golfcube = golf() >>> fig, ax = plt.subplots() - >>> golfcube.show_cube('velocity', style='fence', ax=ax) # doctest: +SKIP + >>> golfcube.show_cube("velocity", style="fence", ax=ax) # doctest: +SKIP """ try: import pyvista as pv diff --git a/deltametrics/mask.py b/deltametrics/mask.py index 37c4a51e..118f9f55 100644 --- a/deltametrics/mask.py +++ b/deltametrics/mask.py @@ -349,12 +349,10 @@ class ElevationMask(ThresholdValueMask): >>> from deltametrics.sample_data.sample_data import golf >>> golfcube = golf() - >>> emsk = ElevationMask( - ... golfcube['eta'][-1, :, :], - ... elevation_threshold=0) + >>> emsk = ElevationMask(golfcube["eta"][-1, :, :], elevation_threshold=0) >>> fig, ax = plt.subplots(1, 2, figsize=(8, 4)) - >>> golfcube.quick_show('eta', idx=-1, ax=ax[0]) + >>> golfcube.quick_show("eta", idx=-1, ax=ax[0]) >>> emsk.show(ax=ax[1]) """ @@ -446,12 +444,8 @@ class FlowMask(ThresholdValueMask): >>> from deltametrics.sample_data.sample_data import golf >>> golfcube = golf() - >>> fvmsk = FlowMask( - ... golfcube['velocity'][-1, :, :], - ... flow_threshold=0.3) - >>> fdmsk = FlowMask( - ... golfcube['discharge'][-1, :, :], - ... flow_threshold=4) + >>> fvmsk = FlowMask(golfcube["velocity"][-1, :, :], flow_threshold=0.3) + >>> fdmsk = FlowMask(golfcube["discharge"][-1, :, :], flow_threshold=4) >>> fig, ax = plt.subplots(1, 2) >>> fvmsk.show(ax=ax[0]) @@ -523,13 +517,14 @@ class ChannelMask(BaseMask): >>> golfcube = golf() >>> cmsk = ChannelMask( - ... golfcube['eta'][-1, :, :], - ... golfcube['velocity'][-1, :, :], + ... golfcube["eta"][-1, :, :], + ... golfcube["velocity"][-1, :, :], ... elevation_threshold=0, - ... flow_threshold=0.3) + ... flow_threshold=0.3, + ... ) >>> fig, ax = plt.subplots(1, 2, figsize=(8, 4)) - >>> golfcube.quick_show('eta', idx=-1, ax=ax[0]) + >>> golfcube.quick_show("eta", idx=-1, ax=ax[0]) >>> cmsk.show(ax=ax[1]) """ @@ -589,22 +584,18 @@ def from_mask(*args, **kwargs): Create the ElevationMask - >>> emsk = ElevationMask( - ... golfcube['eta'][-1, :, :], - ... elevation_threshold=0) + >>> emsk = ElevationMask(golfcube["eta"][-1, :, :], elevation_threshold=0) Create the FlowMask - >>> fmsk = FlowMask( - ... golfcube['velocity'][-1, :, :], - ... flow_threshold=0.3) + >>> fmsk = FlowMask(golfcube["velocity"][-1, :, :], flow_threshold=0.3) Make the ChannelMask from the ElevationMask and FlowMask >>> cmsk = ChannelMask.from_mask(emsk, fmsk) >>> fig, ax = plt.subplots(1, 2, figsize=(8, 4)) - >>> golfcube.quick_show('eta', idx=-1, ax=ax[0]) + >>> golfcube.quick_show("eta", idx=-1, ax=ax[0]) >>> cmsk.show(ax=ax[1]) """ if len(args) == 2: @@ -772,12 +763,10 @@ class WetMask(BaseMask): >>> from deltametrics.sample_data.sample_data import golf >>> golfcube = golf() - >>> wmsk = WetMask( - ... golfcube['eta'][-1, :, :], - ... elevation_threshold=0) + >>> wmsk = WetMask(golfcube["eta"][-1, :, :], elevation_threshold=0) >>> fig, ax = plt.subplots(1, 2, figsize=(8, 4)) - >>> golfcube.quick_show('eta', idx=-1, ax=ax[0]) + >>> golfcube.quick_show("eta", idx=-1, ax=ax[0]) >>> wmsk.show(ax=ax[1]) """ @@ -988,12 +977,10 @@ class LandMask(BaseMask): >>> from deltametrics.sample_data.sample_data import golf >>> golfcube = golf() - >>> lmsk = LandMask( - ... golfcube['eta'][-1, :, :], - ... elevation_threshold=0) + >>> lmsk = LandMask(golfcube["eta"][-1, :, :], elevation_threshold=0) >>> fig, ax = plt.subplots(1, 2, figsize=(8, 4)) - >>> golfcube.quick_show('eta', idx=-1, ax=ax[0]) + >>> golfcube.quick_show("eta", idx=-1, ax=ax[0]) >>> lmsk.show(ax=ax[1]) """ @@ -1235,12 +1222,10 @@ class ShorelineMask(BaseMask): >>> from deltametrics.sample_data.sample_data import golf >>> golfcube = golf() - >>> smsk = ShorelineMask( - ... golfcube['eta'][-1, :, :], - ... elevation_threshold=0) + >>> smsk = ShorelineMask(golfcube["eta"][-1, :, :], elevation_threshold=0) >>> fig, ax = plt.subplots(1, 2, figsize=(8, 4)) - >>> golfcube.quick_show('eta', idx=-1, ax=ax[0]) + >>> golfcube.quick_show("eta", idx=-1, ax=ax[0]) >>> smsk.show(ax=ax[1]) """ @@ -1602,12 +1587,10 @@ class EdgeMask(BaseMask): >>> from deltametrics.sample_data.sample_data import golf >>> golfcube = golf() - >>> edgmsk = EdgeMask( - ... golfcube['eta'][-1, :, :], - ... elevation_threshold=0) + >>> edgmsk = EdgeMask(golfcube["eta"][-1, :, :], elevation_threshold=0) >>> fig, ax = plt.subplots(1, 2, figsize=(8, 4)) - >>> golfcube.quick_show('eta', idx=-1, ax=ax[0]) + >>> golfcube.quick_show("eta", idx=-1, ax=ax[0]) >>> edgmsk.show(ax=ax[1]) """ @@ -1844,13 +1827,14 @@ class CenterlineMask(BaseMask): >>> golfcube = golf() >>> cntmsk = CenterlineMask( - ... golfcube['eta'][-1, :, :], - ... golfcube['velocity'][-1, :, :], + ... golfcube["eta"][-1, :, :], + ... golfcube["velocity"][-1, :, :], ... elevation_threshold=0, - ... flow_threshold=0.3) + ... flow_threshold=0.3, + ... ) >>> fig, ax = plt.subplots(1, 2, figsize=(8, 4)) - >>> golfcube.quick_show('eta', idx=-1, ax=ax[0]) + >>> golfcube.quick_show("eta", idx=-1, ax=ax[0]) >>> cntmsk.show(ax=ax[1]) """ @@ -2129,12 +2113,12 @@ class GeometricMask(BaseMask): >>> from deltametrics.sample_data.sample_data import golf >>> golfcube = golf() - >>> arr = golfcube['eta'][-1, :, :] + >>> arr = golfcube["eta"][-1, :, :] >>> gmsk = GeometricMask(arr) Define an angular mask to cover part of the domain from pi/4 to pi/2. - >>> gmsk.angular(np.pi/4, np.pi/2) + >>> gmsk.angular(np.pi / 4, np.pi / 2) Further mask this region by defining bounds in the radial direction. @@ -2144,7 +2128,7 @@ class GeometricMask(BaseMask): >>> fig, ax = plt.subplots(1, 2, figsize=(8, 4)) >>> gmsk.show(ax=ax[0]) - >>> _ = ax[1].imshow(golfcube['eta'][-1, :, :]*gmsk.mask) + >>> _ = ax[1].imshow(golfcube["eta"][-1, :, :] * gmsk.mask) >>> _ = ax[1].set_xticks([]) >>> _ = ax[1].set_yticks([]) """ @@ -2223,12 +2207,11 @@ def __init__(self, *args, origin=None, **kwargs): >>> arr = np.random.uniform(size=(100, 200)) >>> gmsk0 = GeometricMask(arr) - >>> gmsk0.angular(np.pi/4, np.pi/2) + >>> gmsk0.angular(np.pi / 4, np.pi / 2) >>> gmsk1 = GeometricMask( - ... (100, 200), angular=dict( - ... theta1=np.pi/4, theta2=np.pi/2) - ... ) + ... (100, 200), angular=dict(theta1=np.pi / 4, theta2=np.pi / 2) + ... ) >>> fig, ax = plt.subplots(1, 2) >>> gmsk0.show(ax[0]) @@ -2325,21 +2308,21 @@ def angular(self, theta1=0, theta2=np.pi): >>> from deltametrics.sample_data.sample_data import golf >>> golfcube = golf() - >>> arr = golfcube['eta'][-1, :, :] + >>> arr = golfcube["eta"][-1, :, :] >>> gmsk = GeometricMask(arr) Define an angular mask to cover part of the domain from 0 to pi/3 - >>> gmsk.angular(0, np.pi/3) + >>> gmsk.angular(0, np.pi / 3) Visualize the mask: >>> fig, ax = plt.subplots(1, 2, figsize=(8, 4)) - >>> gmsk.show(ax=ax[0], title='Binary Mask') - >>> _ = ax[1].imshow(golfcube['eta'][-1, :, :] * gmsk.mask) + >>> gmsk.show(ax=ax[0], title="Binary Mask") + >>> _ = ax[1].imshow(golfcube["eta"][-1, :, :] * gmsk.mask) >>> _ = ax[1].set_xticks([]) >>> _ = ax[1].set_yticks([]) - >>> _ = ax[1].set_title('Mask * Topography') + >>> _ = ax[1].set_title("Mask * Topography") """ if (self._L / self._W) > 0.5: raise ValueError("Width of input array must exceed 2x length.") @@ -2387,7 +2370,7 @@ def circular(self, rad1=0, rad2=None, origin=None): >>> from deltametrics.sample_data.sample_data import golf >>> golfcube = golf() - >>> arr = golfcube['eta'][-1, :, :] + >>> arr = golfcube["eta"][-1, :, :] >>> gmsk = GeometricMask(arr) Define an circular mask to exclude region near the inlet @@ -2397,11 +2380,11 @@ def circular(self, rad1=0, rad2=None, origin=None): Visualize the mask: >>> fig, ax = plt.subplots(1, 2, figsize=(8, 4)) - >>> gmsk.show(ax=ax[0], title='Binary Mask') - >>> _ = ax[1].imshow(golfcube['eta'][-1, :, :] * gmsk.mask) + >>> gmsk.show(ax=ax[0], title="Binary Mask") + >>> _ = ax[1].imshow(golfcube["eta"][-1, :, :] * gmsk.mask) >>> _ = ax[1].set_xticks([]) >>> _ = ax[1].set_yticks([]) - >>> _ = ax[1].set_title('Mask * Topography') + >>> _ = ax[1].set_title("Mask * Topography") """ if origin is None: _xc = self._xc @@ -2453,7 +2436,7 @@ def strike(self, ind1=0, ind2=None): >>> from deltametrics.sample_data.sample_data import golf >>> golfcube = golf() - >>> arr = golfcube['eta'][-1, :, :] + >>> arr = golfcube["eta"][-1, :, :] >>> gmsk = GeometricMask(arr) Define a mask that isolates the region 20-50 pixels from the inlet @@ -2463,11 +2446,11 @@ def strike(self, ind1=0, ind2=None): Visualize the mask: >>> fig, ax = plt.subplots(1, 2, figsize=(8, 4)) - >>> gmsk.show(ax=ax[0], title='Binary Mask') - >>> _ = ax[1].imshow(golfcube['eta'][-1, :, :] * gmsk.mask) + >>> gmsk.show(ax=ax[0], title="Binary Mask") + >>> _ = ax[1].imshow(golfcube["eta"][-1, :, :] * gmsk.mask) >>> _ = ax[1].set_xticks([]) >>> _ = ax[1].set_yticks([]) - >>> _ = ax[1].set_title('Mask * Topography') + >>> _ = ax[1].set_title("Mask * Topography") """ if ind2 is None: ind2 = self._L @@ -2506,7 +2489,7 @@ def dip(self, ind1=0, ind2=None): >>> from deltametrics.sample_data.sample_data import golf >>> golfcube = golf() - >>> arr = golfcube['eta'][-1, :, :] + >>> arr = golfcube["eta"][-1, :, :] >>> gmsk = GeometricMask(arr) Define mask with width of 50 px. inline with the inlet @@ -2516,11 +2499,11 @@ def dip(self, ind1=0, ind2=None): Visualize the mask: >>> fig, ax = plt.subplots(1, 2, figsize=(8, 4)) - >>> gmsk.show(ax=ax[0], title='Binary Mask') - >>> _ = ax[1].imshow(golfcube['eta'][-1, :, :] * gmsk.mask) + >>> gmsk.show(ax=ax[0], title="Binary Mask") + >>> _ = ax[1].imshow(golfcube["eta"][-1, :, :] * gmsk.mask) >>> _ = ax[1].set_xticks([]) >>> _ = ax[1].set_yticks([]) - >>> _ = ax[1].set_title('Mask * Topography') + >>> _ = ax[1].set_title("Mask * Topography") """ temp_mask = np.zeros_like(self._mask) if ind2 is None: @@ -2579,11 +2562,11 @@ class DepositMask(BaseMask): >>> golfcube = golf() >>> deposit_mask = DepositMask( - ... golfcube['eta'][-1, :, :], - ... background_value=golfcube['eta'][0, :, :]) + ... golfcube["eta"][-1, :, :], background_value=golfcube["eta"][0, :, :] + ... ) >>> >>> fig, ax = plt.subplots(1, 2) - >>> golfcube.quick_show('eta', ax=ax[0]) + >>> golfcube.quick_show("eta", ax=ax[0]) >>> deposit_mask.show(ax=ax[1]) """ diff --git a/deltametrics/mobility.py b/deltametrics/mobility.py index 512dee10..c0327bbb 100644 --- a/deltametrics/mobility.py +++ b/deltametrics/mobility.py @@ -742,20 +742,24 @@ def channel_presence(chmap): >>> from deltametrics.sample_data.sample_data import golf >>> golfcube = golf() - >>> (x, y) = np.shape(golfcube['eta'][-1, ...]) + >>> (x, y) = np.shape(golfcube["eta"][-1, ...]) Calculate channel masks/presence over final 5 timesteps >>> chmap = np.zeros((5, x, y)) # initialize channel map >>> for i in np.arange(-5, 0): ... chmap[i, ...] = ChannelMask( - ... golfcube['eta'][i, ...], golfcube['velocity'][i, ...], - ... elevation_threshold=0, flow_threshold=0).mask + ... golfcube["eta"][i, ...], + ... golfcube["velocity"][i, ...], + ... elevation_threshold=0, + ... flow_threshold=0, + ... ).mask + ... >>> >>> fig, ax = plt.subplots(1, 2) - >>> golfcube.quick_show('eta', ax=ax[0]) # final delta - >>> p = ax[1].imshow(channel_presence(chmap), cmap='Blues') - >>> _ = append_colorbar(p, ax[1], label='Channelized Time') + >>> golfcube.quick_show("eta", ax=ax[0]) # final delta + >>> p = ax[1].imshow(channel_presence(chmap), cmap="Blues") + >>> _ = append_colorbar(p, ax[1], label="Channelized Time") """ tmp_chans = None # instantiate if isinstance(chmap, mask.ChannelMask) is True: @@ -874,23 +878,26 @@ def calculate_channelized_response_variance( Calculate the CRV on the "Red" band >>> crv_mag, slopes, crv = calculate_channelized_response_variance( - ... img['red'].data, threshold=0.0, - ... normalize_input=True, normalize_output=True) + ... img["red"].data, + ... threshold=0.0, + ... normalize_input=True, + ... normalize_output=True, + ... ) Plot the results >>> fig, ax = plt.subplots(1, 3, figsize=(13, 5)) >>> i0 = ax[0].imshow(crv_mag, vmin=0, vmax=1) - >>> _ = ax[0].set_title('CRV Magnitude') + >>> _ = ax[0].set_title("CRV Magnitude") >>> _ = append_colorbar(i0, ax=ax[0], size=10) >>> s_ex = np.max([np.abs(slopes.min()), slopes.max()]) - >>> i1 = ax[1].imshow(slopes, vmin=-1*s_ex, vmax=s_ex, cmap='PuOr') - >>> _ = ax[1].set_title('CRV Slopes') + >>> i1 = ax[1].imshow(slopes, vmin=-1 * s_ex, vmax=s_ex, cmap="PuOr") + >>> _ = ax[1].set_title("CRV Slopes") >>> _ = append_colorbar(i1, ax=ax[1], size=10) - >>> i2 = ax[2].imshow(crv, vmin=-1, vmax=1, cmap='seismic') - >>> _ = ax[2].set_title('Directional CRV') + >>> i2 = ax[2].imshow(crv, vmin=-1, vmax=1, cmap="seismic") + >>> _ = ax[2].set_title("Directional CRV") >>> _ = append_colorbar(i2, ax=ax[2], size=10) - >>> _ = fig.suptitle('CRV of Red band from imagery from Savi et al 2020') + >>> _ = fig.suptitle("CRV of Red band from imagery from Savi et al 2020") """ # normalize the input array if desired if normalize_input is True: diff --git a/deltametrics/plan.py b/deltametrics/plan.py index fda02a40..4b16cb49 100644 --- a/deltametrics/plan.py +++ b/deltametrics/plan.py @@ -366,8 +366,8 @@ def show( >>> golfcube = golf() >>> planform = Planform(golfcube, idx=70) >>> fig, ax = plt.subplots(1, 2) - >>> _ = planform.show('eta', ax=ax[0]) - >>> _ = planform.show('velocity', ax=ax[1]) + >>> _ = planform.show("eta", ax=ax[0]) + >>> _ = planform.show("velocity", ax=ax[1]) """ from deltametrics.cube import BaseCube @@ -562,9 +562,7 @@ class OpeningAnglePlanform(SpecialtyPlanform): >>> from deltametrics.sample_data.sample_data import golf >>> golfcube = golf() - >>> _EM = ElevationMask( - ... golfcube['eta'][-1, :, :], - ... elevation_threshold=0) + >>> _EM = ElevationMask(golfcube["eta"][-1, :, :], elevation_threshold=0) >>> # extract a mask of area below sea level as the >>> # inverse of the ElevationMask @@ -580,16 +578,17 @@ class OpeningAnglePlanform(SpecialtyPlanform): >>> from deltametrics.plot import append_colorbar >>> fig, ax = plt.subplots(1, 3, figsize=(10, 4)) - >>> golfcube.quick_show('eta', idx=-1, ax=ax[0]) - >>> im1 = ax[1].imshow(OAP.below_mask, cmap='Greys_r') - >>> im2 = ax[2].imshow(OAP.opening_angles, cmap='jet') + >>> golfcube.quick_show("eta", idx=-1, ax=ax[0]) + >>> im1 = ax[1].imshow(OAP.below_mask, cmap="Greys_r") + >>> im2 = ax[2].imshow(OAP.opening_angles, cmap="jet") >>> _ = append_colorbar(im2, ax=ax[2]) - >>> _ = ax[0].set_title('input elevation data') - >>> _ = ax[1].set_title('OAP.below_mask') - >>> _ = ax[2].set_title('OAP.opening_angles') + >>> _ = ax[0].set_title("input elevation data") + >>> _ = ax[1].set_title("OAP.below_mask") + >>> _ = ax[2].set_title("OAP.opening_angles") >>> for i in range(1, 3): ... _ = ax[i].set_xticks([]) ... _ = ax[i].set_yticks([]) + ... """ @staticmethod @@ -634,8 +633,8 @@ def from_elevation_data(elevation_data, **kwargs): >>> golfcube = golf() >>> OAP = OpeningAnglePlanform.from_elevation_data( - ... golfcube['eta'][-1, :, :], - ... elevation_threshold=0) + ... golfcube["eta"][-1, :, :], elevation_threshold=0 + ... ) """ # make a temporary mask _em = ElevationMask(elevation_data, **kwargs) @@ -669,12 +668,9 @@ def from_ElevationMask(elevation_mask, **kwargs): >>> from deltametrics.sample_data.sample_data import golf >>> golfcube = golf() - >>> _EM = ElevationMask( - ... golfcube['eta'][-1, :, :], - ... elevation_threshold=0) + >>> _EM = ElevationMask(golfcube["eta"][-1, :, :], elevation_threshold=0) - >>> OAP = OpeningAnglePlanform.from_ElevationMask( - ... _EM) + >>> OAP = OpeningAnglePlanform.from_ElevationMask(_EM) """ if not isinstance(elevation_mask, ElevationMask): raise TypeError("Must be type: ElevationMask.") @@ -888,9 +884,7 @@ class MorphologicalPlanform(SpecialtyPlanform): >>> from deltametrics.sample_data.sample_data import golf >>> golfcube = golf() - >>> EM = ElevationMask( - ... golfcube['eta'][-1, :, :], - ... elevation_threshold=0) + >>> EM = ElevationMask(golfcube["eta"][-1, :, :], elevation_threshold=0) >>> MP = MorphologicalPlanform(EM, 10) @@ -902,15 +896,15 @@ class MorphologicalPlanform(SpecialtyPlanform): >>> from deltametrics.plot import append_colorbar >>> fig, ax = plt.subplots(1, 2, figsize=(7.5, 4)) - >>> golfcube.quick_show('eta', idx=-1, ax=ax[0]) - >>> im1 = ax[1].imshow(MP.mean_image, - ... cmap='cividis') + >>> golfcube.quick_show("eta", idx=-1, ax=ax[0]) + >>> im1 = ax[1].imshow(MP.mean_image, cmap="cividis") >>> _ = append_colorbar(im1, ax=ax[1]) - >>> _ = ax[0].set_title('input elevation data') - >>> _ = ax[1].set_title('MP.mean_image') + >>> _ = ax[0].set_title("input elevation data") + >>> _ = ax[1].set_title("MP.mean_image") >>> for i in range(1, 2): ... _ = ax[i].set_xticks([]) ... _ = ax[i].set_yticks([]) + ... """ @staticmethod @@ -948,9 +942,8 @@ def from_elevation_data(elevation_data, max_disk, **kwargs): >>> golfcube = golf() >>> MP = MorphologicalPlanform.from_elevation_data( - ... golfcube['eta'][-1, :, :], - ... elevation_threshold=0, - ... max_disk=3) + ... golfcube["eta"][-1, :, :], elevation_threshold=0, max_disk=3 + ... ) """ # make a temporary mask _em = ElevationMask(elevation_data, **kwargs) @@ -1157,17 +1150,18 @@ def compute_land_area(land_mask): >>> golf = golf() >>> lm = LandMask( - ... golf['eta'][-1, :, :], - ... elevation_threshold=golf.meta['H_SL'][-1], - ... elevation_offset=-0.5) + ... golf["eta"][-1, :, :], + ... elevation_threshold=golf.meta["H_SL"][-1], + ... elevation_offset=-0.5, + ... ) - >>> lm.trim_mask(length=golf.meta['L0'].data+1) + >>> lm.trim_mask(length=golf.meta["L0"].data + 1) >>> land_area = compute_land_area(lm) >>> fig, ax = plt.subplots() >>> lm.show(ax=ax, ticks=True) - >>> _ = ax.set_title(f'Land area is {land_area/1e6:.1f} km$^2$') + >>> _ = ax.set_title(f"Land area is {land_area/1e6:.1f} km$^2$") """ # extract data from masks if isinstance(land_mask, LandMask): @@ -1236,24 +1230,20 @@ def compute_shoreline_roughness(shore_mask, land_mask, **kwargs): Early in model run >>> lm0 = LandMask( - ... golf['eta'][15, :, :], - ... elevation_threshold=0, - ... elevation_offset=-0.5) + ... golf["eta"][15, :, :], elevation_threshold=0, elevation_offset=-0.5 + ... ) >>> sm0 = ShorelineMask( - ... golf['eta'][15, :, :], - ... elevation_threshold=0, - ... elevation_offset=-0.5) + ... golf["eta"][15, :, :], elevation_threshold=0, elevation_offset=-0.5 + ... ) Late in model run >>> lm1 = LandMask( - ... golf['eta'][-1, :, :], - ... elevation_threshold=0, - ... elevation_offset=-0.5) + ... golf["eta"][-1, :, :], elevation_threshold=0, elevation_offset=-0.5 + ... ) >>> sm1 = ShorelineMask( - ... golf['eta'][-1, :, :], - ... elevation_threshold=0, - ... elevation_offset=-0.5) + ... golf["eta"][-1, :, :], elevation_threshold=0, elevation_offset=-0.5 + ... ) Let's take a quick peek at the masks that we have created. @@ -1268,10 +1258,10 @@ def compute_shoreline_roughness(shore_mask, land_mask, **kwargs): land-water boundary that is not really a part of the delta. We use the :meth:`~deltametrics.mask.BaseMask.trim_mask` method to trim a mask. - >>> lm0.trim_mask(length=golf.meta['L0'].data+1) - >>> sm0.trim_mask(length=golf.meta['L0'].data+1) - >>> lm1.trim_mask(length=golf.meta['L0'].data+1) - >>> sm1.trim_mask(length=golf.meta['L0'].data+1) + >>> lm0.trim_mask(length=golf.meta["L0"].data + 1) + >>> sm0.trim_mask(length=golf.meta["L0"].data + 1) + >>> lm1.trim_mask(length=golf.meta["L0"].data + 1) + >>> sm1.trim_mask(length=golf.meta["L0"].data + 1) >>> fig, ax = plt.subplots(1, 2, figsize=(8, 3)) >>> lm0.show(ax=ax[0]) @@ -1289,10 +1279,10 @@ def compute_shoreline_roughness(shore_mask, land_mask, **kwargs): Make the plot >>> fig, ax = plt.subplots(1, 2, figsize=(6, 3)) - >>> golf.quick_show('eta', idx=15, ax=ax[0]) - >>> _ = ax[0].set_title('roughness = {:.2f}'.format(rgh0)) - >>> golf.quick_show('eta', idx=-1, ax=ax[1]) - >>> _ = ax[1].set_title('roughness = {:.2f}'.format(rgh1)) + >>> golf.quick_show("eta", idx=15, ax=ax[0]) + >>> _ = ax[0].set_title("roughness = {:.2f}".format(rgh0)) + >>> golf.quick_show("eta", idx=-1, ax=ax[1]) + >>> _ = ax[1].set_title("roughness = {:.2f}".format(rgh1)) """ # extract data from masks if isinstance(land_mask, LandMask): @@ -1380,16 +1370,14 @@ def compute_shoreline_length(shore_mask, origin=(0, 0), return_line=False): Early in model run >>> sm0 = ShorelineMask( - ... golf['eta'][15, :, :], - ... elevation_threshold=0, - ... elevation_offset=-0.5) + ... golf["eta"][15, :, :], elevation_threshold=0, elevation_offset=-0.5 + ... ) Late in model run >>> sm1 = ShorelineMask( - ... golf['eta'][-1, :, :], - ... elevation_threshold=0, - ... elevation_offset=-0.5) + ... golf["eta"][-1, :, :], elevation_threshold=0, elevation_offset=-0.5 + ... ) Compute lengths @@ -1401,11 +1389,11 @@ def compute_shoreline_length(shore_mask, origin=(0, 0), return_line=False): >>> import matplotlib.pyplot as plt >>> fig, ax = plt.subplots(1, 2, figsize=(6, 3)) - >>> golf.quick_show('eta', idx=15, ax=ax[0]) - >>> _ = ax[0].set_title('length = {:.2f}'.format(len0)) - >>> golf.quick_show('eta', idx=-1, ax=ax[1]) - >>> _ = ax[1].plot(line1[:, 0], line1[:, 1], 'r-') - >>> _ = ax[1].set_title('length = {:.2f}'.format(len1)) + >>> golf.quick_show("eta", idx=15, ax=ax[0]) + >>> _ = ax[0].set_title("length = {:.2f}".format(len0)) + >>> golf.quick_show("eta", idx=-1, ax=ax[1]) + >>> _ = ax[1].plot(line1[:, 0], line1[:, 1], "r-") + >>> _ = ax[1].set_title("length = {:.2f}".format(len1)) """ # check if mask or already array if isinstance(shore_mask, ShorelineMask): @@ -1608,22 +1596,22 @@ def compute_shoreline_distance(shore_mask, origin=(0, 0), return_distances=False >>> golf = golf() >>> sm = ShorelineMask( - ... golf['eta'][-1, :, :], - ... elevation_threshold=0, - ... elevation_offset=-0.5) + ... golf["eta"][-1, :, :], elevation_threshold=0, elevation_offset=-0.5 + ... ) Compute mean and stddev distance >>> mean, stddev = compute_shoreline_distance( - ... sm, origin=[golf.meta['CTR'].data, golf.meta['L0'].data]) + ... sm, origin=[golf.meta["CTR"].data, golf.meta["L0"].data] + ... ) Make the plot >>> import matplotlib.pyplot as plt >>> fig, ax = plt.subplots() - >>> golf.quick_show('eta', idx=-1, ticks=True, ax=ax) - >>> _ = ax.set_title('mean = {:.2f}'.format(mean)) + >>> golf.quick_show("eta", idx=-1, ticks=True, ax=ax) + >>> _ = ax.set_title("mean = {:.2f}".format(mean)) """ # check if mask or already array if isinstance(shore_mask, ShorelineMask): @@ -2121,21 +2109,21 @@ def compute_channel_width(channelmask, section=None, return_widths=False): >>> golf = golf() >>> cm = ChannelMask( - ... golf['eta'][-1, :, :], - ... golf['velocity'][-1, :, :], + ... golf["eta"][-1, :, :], + ... golf["velocity"][-1, :, :], ... elevation_threshold=0, - ... flow_threshold=0.3) + ... flow_threshold=0.3, + ... ) >>> sec = CircularSection(golf, radius_idx=40) Compute the metric - >>> m, s, w = compute_channel_width( - ... cm, section=sec, return_widths=True) + >>> m, s, w = compute_channel_width(cm, section=sec, return_widths=True) >>> fig, ax = plt.subplots() >>> cm.show(ax=ax, ticks=True) - >>> sec.show_trace('r-', ax=ax) - >>> _ = ax.set_title(f'mean: {m:.2f}; stddev: {s:.2f}') + >>> sec.show_trace("r-", ax=ax) + >>> _ = ax.set_title(f"mean: {m:.2f}; stddev: {s:.2f}") """ if not (section is None): if issubclass(type(section), BaseSection): @@ -2385,10 +2373,12 @@ def compute_surface_deposit_time(data, surface_idx=-1, **kwargs): >>> fig, ax = plt.subplots(1, 3, figsize=(10, 3)) >>> for i, tol in enumerate([1e-16, 0.01, 0.1]): ... i_sfc_date = compute_surface_deposit_time( - ... golf, surface_idx=-1, stasis_tol=tol) + ... golf, surface_idx=-1, stasis_tol=tol + ... ) ... im = ax[i].imshow(i_sfc_date) ... _ = plt.colorbar(im, ax=ax[i], shrink=0.4) - ... _ = ax[i].set_title(f'stasis_tol={tol}') + ... _ = ax[i].set_title(f"stasis_tol={tol}") + ... """ from deltametrics.cube import DataCube @@ -2453,7 +2443,7 @@ def compute_surface_deposit_age(data, surface_idx, **kwargs): >>> sfc_time = compute_surface_deposit_age(golf, surface_idx=-1) >>> fig, ax = plt.subplots() - >>> _ = ax.imshow(sfc_time, cmap='YlGn_r') + >>> _ = ax.imshow(sfc_time, cmap="YlGn_r") """ sfc_date = compute_surface_deposit_time(data, surface_idx, **kwargs) # handle indices less than 0 diff --git a/deltametrics/plot.py b/deltametrics/plot.py index 5c988ce6..2cd93ba4 100644 --- a/deltametrics/plot.py +++ b/deltametrics/plot.py @@ -39,8 +39,7 @@ class VariableInfo: >>> import matplotlib >>> from deltametrics.plot import VariableInfo - >>> veg = VariableInfo('vegetation_density', - ... cmap='Greens') + >>> veg = VariableInfo("vegetation_density", cmap="Greens") >>> veg.cmap @@ -52,14 +51,15 @@ class VariableInfo: colormap. If instead we wanted just three colors, we could specify the colormap manually: - >>> veg3 = VariableInfo('vegetation_density', - ... cmap=matplotlib.colormaps['Greens'].resampled(3)) + >>> veg3 = VariableInfo( + ... "vegetation_density", cmap=matplotlib.colormaps["Greens"].resampled(3) + ... ) >>> veg3.cmap.N 3 We can then set a more human-readable label for the variable: - >>> veg3.label = 'vegetation density' + >>> veg3.label = "vegetation density" """ def __init__(self, name, **kwargs): @@ -559,11 +559,13 @@ def cartographic_colormap(H_SL=0.0, h=4.5, n=1.0): >>> cmap1, norm1 = cartographic_colormap(H_SL=0, h=5, n=0.5) >>> fig, ax = plt.subplots(1, 2, figsize=(10, 4)) - >>> im0 = ax[0].imshow(golfcube['eta'][-1, ...], origin='lower', - ... cmap=cmap0, norm=norm0) + >>> im0 = ax[0].imshow( + ... golfcube["eta"][-1, ...], origin="lower", cmap=cmap0, norm=norm0 + ... ) >>> cb0 = append_colorbar(im0, ax[0]) - >>> im1 = ax[1].imshow(golfcube['eta'][-1, ...], origin='lower', - ... cmap=cmap1, norm=norm1) + >>> im1 = ax[1].imshow( + ... golfcube["eta"][-1, ...], origin="lower", cmap=cmap1, norm=norm1 + ... ) >>> cb1 = append_colorbar(im1, ax[1]) >>> plt.tight_layout() """ @@ -626,11 +628,13 @@ def vintage_colormap(H_SL=0.0, h=4.5, n=1.0): >>> cmap1, norm1 = vintage_colormap(H_SL=0, h=3, n=0.25) >>> fig, ax = plt.subplots(1, 2, figsize=(10, 4)) - >>> im0 = ax[0].imshow(golfcube['eta'][-1, ...], origin='lower', - ... cmap=cmap0, norm=norm0) + >>> im0 = ax[0].imshow( + ... golfcube["eta"][-1, ...], origin="lower", cmap=cmap0, norm=norm0 + ... ) >>> cb0 = append_colorbar(im0, ax[0]) - >>> im1 = ax[1].imshow(golfcube['eta'][-1, ...], origin='lower', - ... cmap=cmap1, norm=norm1) + >>> im1 = ax[1].imshow( + ... golfcube["eta"][-1, ...], origin="lower", cmap=cmap1, norm=norm1 + ... ) >>> cb1 = append_colorbar(im1, ax[1]) >>> plt.tight_layout() @@ -646,15 +650,12 @@ def vintage_colormap(H_SL=0.0, h=4.5, n=1.0): >>> cmapd, normd = vintage_colormap(H_SL=0, h=20, n=10) >>> fig, ax = plt.subplots( - ... figsize=(4, 2), - ... gridspec_kw=dict( - ... left=0.07, right=0.85, bottom=0.25)) - >>> imd = ax.imshow( - ... X, extent=(-30, 10, 0, 20), - ... cmap=cmapd, norm=normd) + ... figsize=(4, 2), gridspec_kw=dict(left=0.07, right=0.85, bottom=0.25) + ... ) + >>> imd = ax.imshow(X, extent=(-30, 10, 0, 20), cmap=cmapd, norm=normd) >>> cbd = append_colorbar(imd, ax) >>> _ = ax.set_yticks([]) - >>> _ = ax.set_xlabel('elevation [m]') + >>> _ = ax.set_xlabel("elevation [m]") """ # In implementation, we differ from Pearson's version. Pearson's version # takes in `vertSpacing`, a 10-column array with elevations of each @@ -765,15 +766,13 @@ def style_axes_km(*args): >>> golf = golf() - >>> fig, ax = plt.subplots( - ... 3, 1, - ... gridspec_kw=dict(hspace=0.5)) - >>> golf.quick_show('eta', ax=ax[0], ticks=True) + >>> fig, ax = plt.subplots(3, 1, gridspec_kw=dict(hspace=0.5)) + >>> golf.quick_show("eta", ax=ax[0], ticks=True) - >>> golf.quick_show('eta', ax=ax[1], ticks=True) + >>> golf.quick_show("eta", ax=ax[1], ticks=True) >>> style_axes_km(ax[1]) - >>> golf.quick_show('eta', axis=1, idx=10, ax=ax[2]) + >>> golf.quick_show("eta", axis=1, idx=10, ax=ax[2]) >>> ax[2].xaxis.set_major_formatter(style_axes_km) OR use: style_axes_km(ax[2], 'x') @@ -1123,7 +1122,7 @@ def show_one_dimensional_trajectory_to_strata( >>> golfcube = golf() - >>> ets = golfcube['eta'].data[:, 10, 85] # a "real" slice of the model + >>> ets = golfcube["eta"].data[:, 10, 85] # a "real" slice of the model >>> fig, ax = plt.subplots(figsize=(8, 4)) >>> show_one_dimensional_trajectory_to_strata(ets, ax=ax, dz=0.25) @@ -1295,7 +1294,7 @@ def _scale_lightness(rgb, scale_l): Initial color red >>> red = (1.0, 0.0, 0.0) - >>> _ = ax.plot(-1, 1, 'o', color=red) + >>> _ = ax.plot(-1, 1, "o", color=red) Scale from 1 to 0.05 @@ -1305,7 +1304,8 @@ def _scale_lightness(rgb, scale_l): >>> for s, scale in enumerate(scales): ... darker_red = _scale_lightness(red, scale) - ... _ = ax.plot(s, scale, 'o', color=darker_red) + ... _ = ax.plot(s, scale, "o", color=darker_red) + ... """ # https://stackoverflow.com/a/60562502/4038393 # convert rgb to hls @@ -1363,7 +1363,7 @@ def show_histograms(*args, sets=None, ax=None, **kwargs): >>> fig, ax = plt.subplots() >>> show_histograms(*hist_bin_sets, sets=[0, 1, 0, 1, 2], ax=ax) >>> _ = ax.set_xlim((0, 6)) - >>> _ = ax.set_ylabel('density') + >>> _ = ax.set_ylabel("density") """ if not ax: fig, ax = plt.subplots() @@ -1455,7 +1455,7 @@ def aerial_view( >>> from deltametrics.sample_data.sample_data import golf >>> golfcube = golf() - >>> elevation_data = golfcube['eta'][-1, :, :] + >>> elevation_data = golfcube["eta"][-1, :, :] >>> fig, ax = plt.subplots() >>> _ = aerial_view(elevation_data, ax=ax) @@ -1560,35 +1560,36 @@ def overlay_sparse_array( >>> from deltametrics.sample_data.sample_data import golf >>> golfcube = golf() - >>> elevation_data = golfcube['eta'][-1, :, :] - >>> sparse_data = golfcube['discharge'][-1, ...] + >>> elevation_data = golfcube["eta"][-1, :, :] + >>> sparse_data = golfcube["discharge"][-1, ...] >>> fig, ax = plt.subplots(1, 3, figsize=(8, 3)) >>> for axi in ax.ravel(): ... _ = aerial_view(elevation_data, ax=axi) + ... >>> _ = overlay_sparse_array( - ... sparse_data, ax=ax[0]) # default clip is (None, 90) - >>> _ = overlay_sparse_array( - ... sparse_data, alpha_clip=(None, None), ax=ax[1]) - >>> _ = overlay_sparse_array( - ... sparse_data, alpha_clip=(70, 90), ax=ax[2]) + ... sparse_data, ax=ax[0] + ... ) # default clip is (None, 90) + >>> _ = overlay_sparse_array(sparse_data, alpha_clip=(None, None), ax=ax[1]) + >>> _ = overlay_sparse_array(sparse_data, alpha_clip=(70, 90), ax=ax[2]) >>> plt.tight_layout() >>> fig, ax = plt.subplots(1, 3, figsize=(8, 3)) >>> for axi in ax.ravel(): ... _ = aerial_view(elevation_data, ax=axi) + ... >>> _ = overlay_sparse_array( - ... sparse_data, ax=ax[0], - ... clip_type='value') # default clip is (None, 90) + ... sparse_data, ax=ax[0], clip_type="value" + ... ) # default clip is (None, 90) >>> _ = overlay_sparse_array( - ... sparse_data, ax=ax[1], - ... alpha_clip=(None, 0.2), clip_type='value') + ... sparse_data, ax=ax[1], alpha_clip=(None, 0.2), clip_type="value" + ... ) >>> _ = overlay_sparse_array( - ... sparse_data, ax=ax[2], - ... alpha_clip=(0.4, 0.6), clip_type='value') + ... sparse_data, ax=ax[2], alpha_clip=(0.4, 0.6), clip_type="value" + ... ) >>> plt.tight_layout() """ diff --git a/deltametrics/sample_data/sample_data.py b/deltametrics/sample_data/sample_data.py index 4b82e00b..76b6b036 100644 --- a/deltametrics/sample_data/sample_data.py +++ b/deltametrics/sample_data/sample_data.py @@ -72,6 +72,7 @@ def golf(): ... _ = ax[i].set_title(f"t = {t}") ... _ = ax[i].axes.get_xaxis().set_ticks([]) ... _ = ax[i].axes.get_yaxis().set_ticks([]) + ... >>> _ = ax[0].set_ylabel("dim1 direction") >>> _ = ax[0].set_xlabel("dim2 direction") """ @@ -131,6 +132,7 @@ def xslope(): ... _ = ax[0, i].imshow(xslope0["eta"][t, :, :], vmin=-10, vmax=0.5) ... _ = ax[0, i].set_title(f"t = {t}") ... _ = ax[1, i].imshow(xslope1["eta"][t, :, :], vmin=-10, vmax=0.5) + ... >>> _ = ax[1, 0].set_ylabel("dim1 direction") >>> _ = ax[1, 0].set_xlabel("dim2 direction") @@ -138,6 +140,7 @@ def xslope(): >>> for axi in ax.ravel(): ... _ = axi.axes.get_xaxis().set_ticks([]) ... _ = axi.axes.get_yaxis().set_ticks([]) + ... Parameters ---------- @@ -210,6 +213,7 @@ def aeolian(): ... _ = ax[i].set_title(f"t = {t}") ... _ = ax[i].axes.get_xaxis().set_ticks([]) ... _ = ax[i].axes.get_yaxis().set_ticks([]) + ... >>> _ = ax[0].set_ylabel("northing") >>> _ = ax[0].set_xlabel("easting") """ @@ -249,6 +253,7 @@ def rcm8(): >>> with warnings.catch_warnings(): ... warnings.simplefilter("ignore") ... rcm8 = dm.sample_data.rcm8() + ... >>> nt = 5 >>> ts = np.linspace(0, rcm8["eta"].shape[0] - 1, num=nt, dtype=int) @@ -258,6 +263,7 @@ def rcm8(): ... _ = ax[i].set_title(f"t = {t}") ... _ = ax[i].axes.get_xaxis().set_ticks([]) ... _ = ax[i].axes.get_yaxis().set_ticks([]) + ... >>> _ = ax[0].set_ylabel("y-direction") >>> _ = ax[0].set_xlabel("x-direction") """ @@ -304,6 +310,7 @@ def landsat(): ... _ = ax[i].set_title(f"year = {landsat.t[i]}") ... _ = ax[i].axes.get_xaxis().set_ticks([]) ... _ = ax[i].axes.get_yaxis().set_ticks([]) + ... """ landsat_path = _get_landsat_path() return DataCube(landsat_path) @@ -368,6 +375,7 @@ def savi2020(): ... _ = ax[0, i].set_title(f"t = {ts_i[i]}") ... _ = ax[1, i].imshow(scans["eta"][ts_s[i], :, :]) ... _ = ax[1, i].set_title(f"t = {ts_s[i]}") + ... >>> _ = ax[1, 0].set_ylabel("dim1 direction") >>> _ = ax[1, 0].set_xlabel("dim2 direction") diff --git a/deltametrics/section.py b/deltametrics/section.py index 7d8b0895..bfc34cda 100644 --- a/deltametrics/section.py +++ b/deltametrics/section.py @@ -575,9 +575,8 @@ def show( >>> from deltametrics.section import StrikeSection >>> golfcube = golf() - >>> golfcube.register_section( - ... 'demo', StrikeSection(distance_idx=5)) - >>> golfcube.sections['demo'].show('velocity') + >>> golfcube.register_section("demo", StrikeSection(distance_idx=5)) + >>> golfcube.sections["demo"].show("velocity") Note that the last line above is functionally equivalent to ``golfcube.show_section('demo', 'velocity')``. @@ -587,19 +586,26 @@ def show( >>> import matplotlib.pyplot as plt - >>> golfcube.stratigraphy_from('eta') - >>> golfcube.register_section( - ... 'demo', StrikeSection(distance=250)) + >>> golfcube.stratigraphy_from("eta") + >>> golfcube.register_section("demo", StrikeSection(distance=250)) >>> fig, ax = plt.subplots(4, 1, sharex=True, figsize=(6, 9)) - >>> golfcube.sections['demo'].show('depth', data='spacetime', - ... ax=ax[0], label='spacetime') - >>> golfcube.sections['demo'].show('depth', data='preserved', - ... ax=ax[1], label='preserved') - >>> golfcube.sections['demo'].show('depth', data='stratigraphy', - ... ax=ax[2], label='quick stratigraphy') - >>> golfcube.sections['demo'].show('depth', style='lines', data='stratigraphy', - ... ax=ax[3], label='quick stratigraphy') # noqa: E501 + >>> golfcube.sections["demo"].show( + ... "depth", data="spacetime", ax=ax[0], label="spacetime" + ... ) + >>> golfcube.sections["demo"].show( + ... "depth", data="preserved", ax=ax[1], label="preserved" + ... ) + >>> golfcube.sections["demo"].show( + ... "depth", data="stratigraphy", ax=ax[2], label="quick stratigraphy" + ... ) + >>> golfcube.sections["demo"].show( + ... "depth", + ... style="lines", + ... data="stratigraphy", + ... ax=ax[3], + ... label="quick stratigraphy", + ... ) # noqa: E501 """ from deltametrics.cube import BaseCube from deltametrics.plot import VariableSet @@ -755,11 +761,12 @@ class PathSection(BaseSection): >>> from deltametrics.section import PathSection >>> golfcube = golf() - >>> golfcube.register_section('path', PathSection( - ... path_idx=np.array([[3, 50], [17, 65], [10, 130]]))) + >>> golfcube.register_section( + ... "path", PathSection(path_idx=np.array([[3, 50], [17, 65], [10, 130]])) + ... ) >>> fig, ax = plt.subplots() - >>> golfcube.quick_show('eta', idx=-1, ax=ax, ticks=True) - >>> golfcube.sections['path'].show_trace('r--', ax=ax) + >>> golfcube.quick_show("eta", idx=-1, ax=ax, ticks=True) + >>> golfcube.sections["path"].show_trace("r--", ax=ax) Parameters ---------- @@ -803,27 +810,30 @@ class PathSection(BaseSection): >>> from deltametrics.section import PathSection >>> golfcube = golf() - >>> golfcube.register_section('path', PathSection( - ... path=np.array([[2000, 2000], [2000, 6000], [600, 7500]]))) + >>> golfcube.register_section( + ... "path", + ... PathSection(path=np.array([[2000, 2000], [2000, 6000], [600, 7500]])), + ... ) >>> >>> # show the location and the "velocity" variable >>> fig, ax = plt.subplots(2, 1, figsize=(8, 4)) - >>> golfcube.quick_show('eta', idx=-1, ax=ax[0], ticks=True) - >>> golfcube.sections['path'].show_trace('r--', ax=ax[0]) - >>> golfcube.sections['path'].show('velocity', ax=ax[1]) + >>> golfcube.quick_show("eta", idx=-1, ax=ax[0], ticks=True) + >>> golfcube.sections["path"].show_trace("r--", ax=ax[0]) + >>> golfcube.sections["path"].show("velocity", ax=ax[1]) Create a `PathSection` that is registered to a `DataCube` at specified indices: >>> golfcube = golf() - >>> golfcube.register_section('path', PathSection( - ... path_idx=np.array([[3, 50], [17, 65], [10, 130]]))) + >>> golfcube.register_section( + ... "path", PathSection(path_idx=np.array([[3, 50], [17, 65], [10, 130]])) + ... ) >>> >>> # show the location and the "velocity" variable >>> fig, ax = plt.subplots(2, 1, figsize=(8, 4)) - >>> golfcube.quick_show('eta', idx=-1, ax=ax[0], ticks=True) - >>> golfcube.sections['path'].show_trace('r--', ax=ax[0]) - >>> golfcube.sections['path'].show('velocity', ax=ax[1]) + >>> golfcube.quick_show("eta", idx=-1, ax=ax[0], ticks=True) + >>> golfcube.sections["path"].show_trace("r--", ax=ax[0]) + >>> golfcube.sections["path"].show("velocity", ax=ax[1]) """ def __init__(self, *args, path=None, path_idx=None, **kwargs): @@ -1029,11 +1039,10 @@ class StrikeSection(LineSection): >>> from deltametrics.section import StrikeSection >>> golfcube = golf() - >>> golfcube.register_section( - ... 'strike', StrikeSection(distance=1500)) + >>> golfcube.register_section("strike", StrikeSection(distance=1500)) >>> fig, ax = plt.subplots() - >>> golfcube.quick_show('eta', idx=-1, ax=ax, ticks=True) - >>> golfcube.sections['strike'].show_trace('r--', ax=ax) + >>> golfcube.quick_show("eta", idx=-1, ax=ax, ticks=True) + >>> golfcube.sections["strike"].show_trace("r--", ax=ax) .. hint:: @@ -1096,25 +1105,25 @@ class StrikeSection(LineSection): >>> from deltametrics.section import StrikeSection >>> golfcube = golf() - >>> golfcube.register_section('strike', StrikeSection(distance=3500)) + >>> golfcube.register_section("strike", StrikeSection(distance=3500)) >>> # show the location and the "velocity" variable >>> fig, ax = plt.subplots(2, 1, figsize=(8, 4)) - >>> golfcube.quick_show('eta', idx=-1, ax=ax[0], ticks=True) - >>> golfcube.sections['strike'].show_trace('r--', ax=ax[0]) - >>> golfcube.sections['strike'].show('velocity', ax=ax[1]) + >>> golfcube.quick_show("eta", idx=-1, ax=ax[0], ticks=True) + >>> golfcube.sections["strike"].show_trace("r--", ax=ax[0]) + >>> golfcube.sections["strike"].show("velocity", ax=ax[1]) Create a `StrikeSection` that is registered to a `DataCube` at specified `distance_idx` index ``=10``, and spans the entire model domain: >>> golfcube = golf() - >>> golfcube.register_section('strike', StrikeSection(distance_idx=10)) + >>> golfcube.register_section("strike", StrikeSection(distance_idx=10)) >>> # show the location and the "velocity" variable >>> fig, ax = plt.subplots(2, 1, figsize=(8, 4)) - >>> golfcube.quick_show('eta', idx=-1, ax=ax[0], ticks=True) - >>> golfcube.sections['strike'].show_trace('r--', ax=ax[0]) - >>> golfcube.sections['strike'].show('velocity', ax=ax[1]) + >>> golfcube.quick_show("eta", idx=-1, ax=ax[0], ticks=True) + >>> golfcube.sections["strike"].show_trace("r--", ax=ax[0]) + >>> golfcube.sections["strike"].show("velocity", ax=ax[1]) Create a `StrikeSection` that is registered to a `StratigraphyCube` at specified `distance` in `dim1` coordinates, and spans only a range in the @@ -1125,13 +1134,14 @@ class StrikeSection(LineSection): >>> golfcube = golf() >>> golfstrat = StratigraphyCube.from_DataCube(golfcube, dz=0.1) >>> golfstrat.register_section( - ... 'strike_part', StrikeSection(distance=1500, length=(2000, 5000))) + ... "strike_part", StrikeSection(distance=1500, length=(2000, 5000)) + ... ) >>> # show the location and the "time" variable >>> fig, ax = plt.subplots(2, 1, figsize=(8, 4)) - >>> golfcube.quick_show('eta', idx=-1, ax=ax[0], ticks=True) - >>> golfstrat.sections['strike_part'].show_trace('r--', ax=ax[0]) - >>> golfstrat.sections['strike_part'].show('time', ax=ax[1]) + >>> golfcube.quick_show("eta", idx=-1, ax=ax[0], ticks=True) + >>> golfstrat.sections["strike_part"].show_trace("r--", ax=ax[0]) + >>> golfstrat.sections["strike_part"].show("time", ax=ax[1]) """ def __init__( @@ -1244,11 +1254,10 @@ class DipSection(LineSection): >>> from deltametrics.section import DipSection >>> golfcube = golf() - >>> golfcube.register_section( - ... 'dip', DipSection(distance=3000)) + >>> golfcube.register_section("dip", DipSection(distance=3000)) >>> fig, ax = plt.subplots() - >>> golfcube.quick_show('eta', idx=-1, ax=ax, ticks=True) - >>> golfcube.sections['dip'].show_trace('r--', ax=ax) + >>> golfcube.quick_show("eta", idx=-1, ax=ax, ticks=True) + >>> golfcube.sections["dip"].show_trace("r--", ax=ax) .. hint:: @@ -1313,25 +1322,25 @@ class DipSection(LineSection): >>> from deltametrics.section import DipSection >>> golfcube = golf() - >>> golfcube.register_section('dip', DipSection(distance=3500)) + >>> golfcube.register_section("dip", DipSection(distance=3500)) >>> # show the location and the "sandfrac" variable >>> fig, ax = plt.subplots(2, 1, figsize=(8, 4)) - >>> golfcube.quick_show('eta', idx=-1, ax=ax[0], ticks=True) - >>> golfcube.sections['dip'].show_trace('r--', ax=ax[0]) - >>> golfcube.sections['dip'].show('sandfrac', ax=ax[1]) + >>> golfcube.quick_show("eta", idx=-1, ax=ax[0], ticks=True) + >>> golfcube.sections["dip"].show_trace("r--", ax=ax[0]) + >>> golfcube.sections["dip"].show("sandfrac", ax=ax[1]) Create a `DipSection` that is registered to a `DataCube` at specified `distance_idx` index ``=75``, and spans the entire model domain: >>> golfcube = golf() - >>> golfcube.register_section('dip75', DipSection(distance_idx=75)) + >>> golfcube.register_section("dip75", DipSection(distance_idx=75)) >>> # show the location and the "sandfrac" variable >>> fig, ax = plt.subplots(2, 1, figsize=(8, 4)) - >>> golfcube.quick_show('eta', idx=-1, ax=ax[0], ticks=True) - >>> golfcube.sections['dip75'].show_trace('r--', ax=ax[0]) - >>> golfcube.sections['dip75'].show('sandfrac', ax=ax[1]) + >>> golfcube.quick_show("eta", idx=-1, ax=ax[0], ticks=True) + >>> golfcube.sections["dip75"].show_trace("r--", ax=ax[0]) + >>> golfcube.sections["dip75"].show("sandfrac", ax=ax[1]) Create a `DipSection` that is registered to a `StratigraphyCube` at specified `distance` in `dim2` coordinates, and spans only a range in the @@ -1342,13 +1351,14 @@ class DipSection(LineSection): >>> golfcube = golf() >>> golfstrat = StratigraphyCube.from_DataCube(golfcube, dz=0.1) >>> golfstrat.register_section( - ... 'dip_part', DipSection(distance=4000, length=(500, 1500))) + ... "dip_part", DipSection(distance=4000, length=(500, 1500)) + ... ) >>> # show the location and the "velocity" variable >>> fig, ax = plt.subplots(2, 1, figsize=(8, 4)) - >>> golfcube.quick_show('eta', idx=-1, ax=ax[0], ticks=True) - >>> golfstrat.sections['dip_part'].show_trace('r--', ax=ax[0]) - >>> golfstrat.sections['dip_part'].show('velocity', ax=ax[1]) + >>> golfcube.quick_show("eta", idx=-1, ax=ax[0], ticks=True) + >>> golfstrat.sections["dip_part"].show_trace("r--", ax=ax[0]) + >>> golfstrat.sections["dip_part"].show("velocity", ax=ax[1]) """ def __init__( @@ -1464,13 +1474,12 @@ class CircularSection(BaseSection): >>> from deltametrics.section import CircularSection >>> golfcube = golf() - >>> golfcube.register_section( - ... 'circular', CircularSection(radius=1200)) + >>> golfcube.register_section("circular", CircularSection(radius=1200)) >>> # show the location and the "velocity" variable >>> fig, ax = plt.subplots() - >>> golfcube.quick_show('eta', idx=-1, ax=ax, ticks=True) - >>> golfcube.sections['circular'].show_trace('r--', ax=ax) + >>> golfcube.quick_show("eta", idx=-1, ax=ax, ticks=True) + >>> golfcube.sections["circular"].show_trace("r--", ax=ax) .. warning:: @@ -1534,14 +1543,13 @@ class CircularSection(BaseSection): >>> from deltametrics.section import CircularSection >>> golfcube = golf() - >>> golfcube.register_section( - ... 'circular', CircularSection(radius=1200)) + >>> golfcube.register_section("circular", CircularSection(radius=1200)) >>> # show the location and the "velocity" variable >>> fig, ax = plt.subplots(2, 1, figsize=(8, 4)) - >>> golfcube.quick_show('eta', idx=-1, ax=ax[0], ticks=True) - >>> golfcube.sections['circular'].show_trace('r--', ax=ax[0]) - >>> golfcube.sections['circular'].show('velocity', ax=ax[1]) + >>> golfcube.quick_show("eta", idx=-1, ax=ax[0], ticks=True) + >>> golfcube.sections["circular"].show_trace("r--", ax=ax[0]) + >>> golfcube.sections["circular"].show("velocity", ax=ax[1]) Create a `CircularSection` that is registered to a `StratigraphyCube` with radius index ``=50``, and the origin against the domain edge (using the @@ -1550,14 +1558,14 @@ class CircularSection(BaseSection): >>> golfcube = golf() >>> golfstrat = StratigraphyCube.from_DataCube(golfcube, dz=0.1) >>> golfstrat.register_section( - ... 'circular', CircularSection(radius_idx=50, origin_idx=(0, 100)) + ... "circular", CircularSection(radius_idx=50, origin_idx=(0, 100)) ... ) >>> # show the location and the "velocity" variable >>> fig, ax = plt.subplots(2, 1, figsize=(8, 4)) - >>> golfcube.quick_show('eta', idx=-1, ax=ax[0], ticks=True) - >>> golfstrat.sections['circular'].show_trace('r--', ax=ax[0]) - >>> golfstrat.sections['circular'].show('velocity', ax=ax[1]) + >>> golfcube.quick_show("eta", idx=-1, ax=ax[0], ticks=True) + >>> golfstrat.sections["circular"].show_trace("r--", ax=ax[0]) + >>> golfstrat.sections["circular"].show("velocity", ax=ax[1]) """ def __init__( @@ -1694,13 +1702,12 @@ class RadialSection(BaseSection): >>> from deltametrics.section import RadialSection >>> golfcube = golf() - >>> golfcube.register_section( - ... 'radial', RadialSection(azimuth=65)) + >>> golfcube.register_section("radial", RadialSection(azimuth=65)) >>> # show the location and the "velocity" variable >>> fig, ax = plt.subplots() - >>> golfcube.quick_show('eta', idx=-1, ax=ax, ticks=True) - >>> golfcube.sections['radial'].show_trace('r--', ax=ax) + >>> golfcube.quick_show("eta", idx=-1, ax=ax, ticks=True) + >>> golfcube.sections["radial"].show_trace("r--", ax=ax) .. important:: @@ -1781,14 +1788,13 @@ class RadialSection(BaseSection): >>> from deltametrics.section import RadialSection >>> golfcube = golf() - >>> golfcube.register_section( - ... 'radial', RadialSection(azimuth=45)) + >>> golfcube.register_section("radial", RadialSection(azimuth=45)) >>> # show the location and the "velocity" variable >>> fig, ax = plt.subplots(2, 1, figsize=(8, 4)) - >>> golfcube.quick_show('eta', idx=-1, ax=ax[0], ticks=True) - >>> golfcube.sections['radial'].show_trace('r--', ax=ax[0]) - >>> golfcube.sections['radial'].show('velocity', ax=ax[1]) + >>> golfcube.quick_show("eta", idx=-1, ax=ax[0], ticks=True) + >>> golfcube.sections["radial"].show_trace("r--", ax=ax[0]) + >>> golfcube.sections["radial"].show("velocity", ax=ax[1]) Create several `RadialSection` objects, spaced out across the domain, connected to a `StratigraphyCube`. Each section should be shorter than @@ -1799,20 +1805,21 @@ class RadialSection(BaseSection): >>> fig, ax = plt.subplots(2, 3, figsize=(9, 3)) >>> ax = ax.flatten() - >>> golfcube.quick_show('eta', idx=-1, ax=ax[1], ticks=True) + >>> golfcube.quick_show("eta", idx=-1, ax=ax[1], ticks=True) >>> ax[1].tick_params(labelsize=8) >>> azims = np.linspace(0, 180, num=5) >>> idxs = [2, 5, 4, 3, 0] # indices in the order to draw to match 0-->180 >>> for i, (azim, idx) in enumerate(zip(azims, idxs)): ... sec = RadialSection(golfstrat, azimuth=azim, length=4000) - ... sec.show_trace('r--', ax=ax[1]) + ... sec.show_trace("r--", ax=ax[1]) ... # sec.show('time', ax=ax[idx], colorbar=False) ... _ = ax[idx].text( - ... 3000, 0, 'azimuth: {0}'.format(azim), ha='center', fontsize=8 + ... 3000, 0, "azimuth: {0}".format(azim), ha="center", fontsize=8 ... ) ... ax[idx].tick_params(labelsize=8) ... _ = ax[idx].set_ylim(-4, 1) + ... """ # @staticmethod diff --git a/deltametrics/strat.py b/deltametrics/strat.py index 3f3f2fc1..3eea4735 100644 --- a/deltametrics/strat.py +++ b/deltametrics/strat.py @@ -92,38 +92,39 @@ def _determine_deposit_from_background(sediment_volume, background): Background determined from initial basin topography >>> background0 = _determine_deposit_from_background( - ... golfcube['sandfrac'], - ... background=golfstrat.Z < golfcube['eta'][0].data) + ... golfcube["sandfrac"], background=golfstrat.Z < golfcube["eta"][0].data + ... ) Background determined from min of bed elevation timeseries >>> background1 = _determine_deposit_from_background( - ... golfcube['sandfrac'], - ... background=(golfstrat.Z < np.min(golfcube['eta'].data, axis=0))) + ... golfcube["sandfrac"], + ... background=(golfstrat.Z < np.min(golfcube["eta"].data, axis=0)), + ... ) Background determined from a fixed sandfrac value >>> background2 = _determine_deposit_from_background( - ... golfcube['sandfrac'], - ... background=0) + ... golfcube["sandfrac"], background=0 + ... ) >>> fig, ax = plt.subplots(2, 2, figsize=(6, 4)) Just below initial basin depth - >>> _ = ax[0, 0].imshow(background0[59], cmap='Greys_r') + >>> _ = ax[0, 0].imshow(background0[59], cmap="Greys_r") Just above initial basin depth - >>> _ = ax[0, 1].imshow(background0[60], cmap='Greys_r') + >>> _ = ax[0, 1].imshow(background0[60], cmap="Greys_r") Just below initial basin depth - >>> _ = ax[1, 0].imshow(background1[59], cmap='Greys_r') + >>> _ = ax[1, 0].imshow(background1[59], cmap="Greys_r") Just below initial basin depth - >>> _ = ax[1, 1].imshow(background2[59], cmap='Greys_r') + >>> _ = ax[1, 1].imshow(background2[59], cmap="Greys_r") >>> plt.tight_layout() """ if background is None: @@ -186,23 +187,21 @@ def compute_net_to_gross(sediment_volume, net_threshold=None, background=None): >>> golfcube = golf() >>> golfstrat = StratigraphyCube.from_DataCube(golfcube, dz=0.1) - >>> background = (golfstrat.Z < np.min(golfcube['eta'].data, axis=0)) + >>> background = golfstrat.Z < np.min(golfcube["eta"].data, axis=0) >>> net_to_gross = compute_net_to_gross( - ... golfstrat['sandfrac'], - ... net_threshold=0.5, - ... background=background) + ... golfstrat["sandfrac"], net_threshold=0.5, background=background + ... ) >>> fig, ax = plt.subplots(1, 2) - >>> im0 = ax[0].imshow( - ... net_to_gross, - ... extent=golfstrat.extent) + >>> im0 = ax[0].imshow(net_to_gross, extent=golfstrat.extent) >>> _ = append_colorbar(im0, ax=ax[0]) >>> im1 = ax[1].imshow( ... net_to_gross, - ... cmap=golfstrat.varset['net_to_gross'].cmap, - ... norm=golfstrat.varset['net_to_gross'].norm, - ... extent=golfstrat.extent) + ... cmap=golfstrat.varset["net_to_gross"].cmap, + ... norm=golfstrat.varset["net_to_gross"].norm, + ... extent=golfstrat.extent, + ... ) >>> _ = append_colorbar(im1, ax=ax[1]) >>> plt.tight_layout() """ @@ -265,19 +264,19 @@ def compute_thickness_surfaces(top_surface, bottom_surface): >>> golfcube = golf() >>> deposit_thickness0 = compute_thickness_surfaces( - ... golfcube['eta'][-1, :, :], - ... golfcube['eta'][0, :, :]) + ... golfcube["eta"][-1, :, :], golfcube["eta"][0, :, :] + ... ) >>> deposit_thickness1 = compute_thickness_surfaces( - ... golfcube['eta'][-1, :, :], - ... np.min(golfcube['eta'], axis=0)) + ... golfcube["eta"][-1, :, :], np.min(golfcube["eta"], axis=0) + ... ) >>> fig, ax = plt.subplots(1, 2) >>> im = ax[0].imshow(deposit_thickness0) >>> _ = append_colorbar(im, ax=ax[0]) - >>> _ = ax[0].set_title('thickness above initial basin') + >>> _ = ax[0].set_title("thickness above initial basin") >>> im = ax[1].imshow(deposit_thickness1) >>> _ = append_colorbar(im, ax=ax[1]) - >>> _ = ax[1].set_title('total deposit thickness') + >>> _ = ax[1].set_title("total deposit thickness") >>> plt.tight_layout() """ difference = top_surface - bottom_surface @@ -378,22 +377,20 @@ def compute_sedimentograph( >>> golfcube = golf() >>> golfstrat = StratigraphyCube.from_DataCube(golfcube, dz=0.1) - >>> background = (golfstrat.Z < np.min(golfcube['eta'].data, axis=0)) + >>> background = golfstrat.Z < np.min(golfcube["eta"].data, axis=0) >>> (sedimentograph, radii, bins) = compute_sedimentograph( - ... golfstrat['sandfrac'], + ... golfstrat["sandfrac"], ... num_sections=50, ... last_section_radius=2750, ... background=background, - ... origin_idx=[3, 100]) + ... origin_idx=[3, 100], + ... ) >>> fig, ax = plt.subplots() - >>> _ = ax.plot( - ... radii, - ... sedimentograph[:, 1], - ... marker='o', ls='-') - >>> _ = ax.set_xlabel('section radius (m)') - >>> _ = ax.set_ylabel(f'fraction > {bins[1]}') + >>> _ = ax.plot(radii, sedimentograph[:, 1], marker="o", ls="-") + >>> _ = ax.set_xlabel("section radius (m)") + >>> _ = ax.set_ylabel(f"fraction > {bins[1]}") .. [1] Liang, M., Van Dyk, C., and Passalacqua, P. (2016), Quantifying the patterns and dynamics of river deltas under conditions of diff --git a/deltametrics/utils.py b/deltametrics/utils.py index 5f825dc9..18f341a0 100644 --- a/deltametrics/utils.py +++ b/deltametrics/utils.py @@ -47,7 +47,7 @@ class NoStratigraphyError(AttributeError): With the `var` argument given as ``'strat_attr'``: - >>> raise NoStratigraphyError(golfcube, 'strat_attr') + >>> raise NoStratigraphyError(golfcube, "strat_attr") Traceback (most recent call last): deltametrics.utils.NoStratigraphyError: 'DataCube' object has no preservation or stratigraphy information. @@ -328,8 +328,8 @@ def line_to_cells(*args): >>> fig, ax = plt.subplots(figsize=(2, 2)) >>> _arr = np.zeros((10, 10)) >>> _arr[y, x] = 1 - >>> _ = ax.imshow(_arr, cmap='gray') - >>> _ = ax.plot([p0[0], p1[0]], [p0[1], p1[1]], 'r-') + >>> _ = ax.imshow(_arr, cmap="gray") + >>> _ = ax.plot([p0[0], p1[0]], [p0[1], p1[1]], "r-") """ # process the args if len(args) == 1: From 669597b0edb2001755ba8f0700d858e69b860e08 Mon Sep 17 00:00:00 2001 From: mcflugen Date: Fri, 20 Dec 2024 11:56:32 -0700 Subject: [PATCH 2/4] apply black to example code in the guides --- docs/source/guides/10min.rst | 35 ++-- ...omparing_speeds_of_stratigraphy_access.rst | 20 +- .../guides/examples/io/setup_any_dataset.rst | 11 +- .../source/guides/examples/plot/show_plan.rst | 11 +- .../guides/examples/plot/show_section.rst | 7 +- .../guides/examples/plot/simple_movie.rst | 7 +- docs/source/guides/subject_guides/mask.rst | 14 +- .../source/guides/subject_guides/mobility.rst | 49 ++--- docs/source/guides/subject_guides/section.rst | 16 +- .../guides/subject_guides/visualization.rst | 38 ++-- docs/source/guides/userguide.rst | 176 ++++++++++-------- 11 files changed, 211 insertions(+), 173 deletions(-) diff --git a/docs/source/guides/10min.rst b/docs/source/guides/10min.rst index 9e853976..13a4333a 100644 --- a/docs/source/guides/10min.rst +++ b/docs/source/guides/10min.rst @@ -7,8 +7,8 @@ For a more in depth guide, be sure to check out the :doc:`userguide`. .. testsetup:: * - import deltametrics as dm - import numpy as np + >>> import deltametrics as dm + >>> import numpy as np All of the documentation in this package assumes that you have imported the DeltaMetrics package as ``dm``: @@ -56,17 +56,17 @@ Slicing a cube returns an instance of :obj:`~deltametrics.cube.CubeVariable`, wh .. doctest:: - >>> type(golfcube['velocity']) + >>> type(golfcube["velocity"]) - >>> type(golfcube['velocity'].data) + >>> type(golfcube["velocity"].data) The underlying xarray object can be directly accessed by using a ``.data`` attribute, however, this is not necessary, and you can slice the `CubeVariable` directly with any valid `numpy` slicing style. For example, we could determine how much the average bed elevation changed at a specific location in the model domain (43, 123), by slicing the ``eta`` variable, and differencing timesteps. .. doctest:: - >>> np.mean( golfcube['eta'][1:,43,123] - golfcube['eta'][:-1,43,123] ) + >>> np.mean(golfcube["eta"][1:, 43, 123] - golfcube["eta"][:-1, 43, 123]) Size: 4B array(0., dtype=float32) Coordinates: @@ -99,10 +99,10 @@ of the Cube at the fortieth (40th) timestep: >>> import matplotlib.pyplot as plt >>> fig, ax = plt.subplots(1, 3) - >>> golfcube.quick_show('eta', idx=40, ax=ax[0]) - >>> golfcube.quick_show('velocity', idx=40, ax=ax[1], ticks=True) - >>> golfcube.quick_show('sandfrac', idx=40, ax=ax[2]) - >>> plt.show() #doctest: +SKIP + >>> golfcube.quick_show("eta", idx=40, ax=ax[0]) + >>> golfcube.quick_show("velocity", idx=40, ax=ax[1], ticks=True) + >>> golfcube.quick_show("sandfrac", idx=40, ax=ax[2]) + >>> plt.show() # doctest: +SKIP .. plot:: guides/10min_three_plans.py @@ -118,7 +118,7 @@ We must directly tell the Cube instance to compute stratigraphy by specifying wh .. doctest:: - >>> golfcube.stratigraphy_from('eta', dz=0.1) + >>> golfcube.stratigraphy_from("eta", dz=0.1) For this example, the stratigraphic computation is relatively fast (< one second), but for large data domains covering a large amount of time, this computation may not be as fast. The stratigraphy computed via `stratigraphy_from` is often referred to as "quick" stratigraphy, and may be helpful for visualizing cross sections of the deposit, but we recommend creating a :obj:`~deltametrics.cube.StratigraphyCube` from a `DataCube` for thorough analysis of stratigraphy. @@ -129,23 +129,26 @@ For a data cube, sections are most easily instantiated by the :obj:`~deltametric .. doctest:: - >>> golfcube.register_section('demo', dm.section.StrikeSection(distance_idx=10)) + >>> golfcube.register_section("demo", dm.section.StrikeSection(distance_idx=10)) which can then be accessed via the :obj:`~deltametrics.cube.Cube.sections` attribute of the Cube. .. doctest:: - >>> golfcube.sections['demo'] + >>> golfcube.sections["demo"] Using the "quick" stratigraphy, we can visualize a few of the available data variables as stratigraphy: .. doctest:: - >>> fig, ax = plt.subplots(5, 1, sharex=True, figsize=(8,5)) + >>> fig, ax = plt.subplots(5, 1, sharex=True, figsize=(8, 5)) >>> ax = ax.flatten() - >>> for i, var in enumerate(['time', 'eta', 'velocity', 'discharge', 'sandfrac']): - ... golfcube.show_section('demo', var, data='stratigraphy', ax=ax[i], label=True) - >>> plt.show() #doctest: +SKIP + >>> for i, var in enumerate(["time", "eta", "velocity", "discharge", "sandfrac"]): + ... golfcube.show_section( + ... "demo", var, data="stratigraphy", ax=ax[i], label=True + ... ) + ... + >>> plt.show() # doctest: +SKIP .. plot:: guides/10min_all_sections_strat.py diff --git a/docs/source/guides/examples/computations/comparing_speeds_of_stratigraphy_access.rst b/docs/source/guides/examples/computations/comparing_speeds_of_stratigraphy_access.rst index 7ff68eaa..32fbadb4 100644 --- a/docs/source/guides/examples/computations/comparing_speeds_of_stratigraphy_access.rst +++ b/docs/source/guides/examples/computations/comparing_speeds_of_stratigraphy_access.rst @@ -12,23 +12,33 @@ Keeping data on disk is advantageous for large datasets, but slows down access c >>> # set up the cubes >>> golfcube = dm.sample_data.golf() >>> stratcube = dm.cube.StratigraphyCube.from_DataCube(golfcube, dz=0.05) - >>> fs, fe = dm.strat.compute_boxy_stratigraphy_volume(golfcube['eta'], golfcube['sandfrac'], dz=0.05) + >>> fs, fe = dm.strat.compute_boxy_stratigraphy_volume( + ... golfcube["eta"], golfcube["sandfrac"], dz=0.05 + ... ) >>> # time extraction from the frozen cube >>> start1 = time.time() >>> for _ in range(100): ... _val = fs[10:20, 31:35, -1:-30:-2] + ... >>> end1 = time.time() >>> # time extraction from the underlying DataCube data on disk >>> start2 = time.time() >>> for _ in range(100): - ... _val = stratcube['sandfrac'].data[10:20, 31:35, -1:-30:-2] + ... _val = stratcube["sandfrac"].data[10:20, 31:35, -1:-30:-2] + ... >>> end2 = time.time() - >>> print("Elapsed time for frozen cube: ", end1-start1, " seconds") #doctest: +SKIP + >>> print( + ... "Elapsed time for frozen cube: ", end1 - start1, " seconds" + ... ) # doctest: +SKIP Elapsed time for frozen cube: 0.00011587142944335938 - >>> print("Elapsed time for on-disk cube: ", end2-start2, " seconds") #doctest: +SKIP + >>> print( + ... "Elapsed time for on-disk cube: ", end2 - start2, " seconds" + ... ) # doctest: +SKIP Elapsed time for on-disk cube: 7.14995002746582 seconds - >>> print("Speed difference: ", (end2-start2)/(end1-start1), " times faster") #doctest: +SKIP + >>> print( + ... "Speed difference: ", (end2 - start2) / (end1 - start1), " times faster" + ... ) # doctest: +SKIP Speed difference: 61705.89300411523 times faster diff --git a/docs/source/guides/examples/io/setup_any_dataset.rst b/docs/source/guides/examples/io/setup_any_dataset.rst index 9fdd63e1..6b84e5ef 100644 --- a/docs/source/guides/examples/io/setup_any_dataset.rst +++ b/docs/source/guides/examples/io/setup_any_dataset.rst @@ -107,8 +107,8 @@ Now, we write out the data to a netCDF file. .. code:: - output_folder = './output' - file_path = os.path.join(output_folder, 'model_output.nc') + output_folder = "./output" + file_path = os.path.join(output_folder, "model_output.nc") .. plot:: :include-source: @@ -247,11 +247,8 @@ If you want a basic workaround, you can create a dictionary inside the input dic .. code:: dict_datacube = dm.cube.DataCube( - data_dict, - dimensions={'time': t, - 'y': y, - 'x': x, - 'meta': {'H_SL': H_SL}}) + data_dict, dimensions={"time": t, "y": y, "x": x, "meta": {"H_SL": H_SL}} + ) But be aware that dimensions will not be attached to the metadata (unless you pass in a `DataArray`), and you cannot use the `.meta` accessor, and instead would need to use ``dict_datacube['meta']['H_SL']``. diff --git a/docs/source/guides/examples/plot/show_plan.rst b/docs/source/guides/examples/plot/show_plan.rst index bfc45328..48836ec3 100644 --- a/docs/source/guides/examples/plot/show_plan.rst +++ b/docs/source/guides/examples/plot/show_plan.rst @@ -18,8 +18,8 @@ You can visualize the data yourself, or use the built-in `show()` method of a `P :context: >>> fig, ax = plt.subplots(1, 2, figsize=(7, 3)) - >>> ax[0].imshow(final['velocity']) # display directly - >>> final.show('velocity', ax=ax[1]) # use the built-in show() + >>> ax[0].imshow(final["velocity"]) # display directly + >>> final.show("velocity", ax=ax[1]) # use the built-in show() >>> plt.show() @@ -30,8 +30,7 @@ StratigraphyCube :include-source: :context: close-figs - >>> golfstrat = dm.cube.StratigraphyCube.from_DataCube( - ... golfcube, dz=0.1) + >>> golfstrat = dm.cube.StratigraphyCube.from_DataCube(golfcube, dz=0.1) >>> minus1 = dm.plan.Planform(golfstrat, z=-1) You can visualize the data yourself, or use the built-in `show()` method of a `Planform`. @@ -41,8 +40,8 @@ You can visualize the data yourself, or use the built-in `show()` method of a `P :context: >>> fig, ax = plt.subplots(1, 2, figsize=(7, 3)) - >>> ax[0].imshow(minus1['velocity']) # display directly - >>> minus1.show('velocity', ax=ax[1]) # use the built-in show() + >>> ax[0].imshow(minus1["velocity"]) # display directly + >>> minus1.show("velocity", ax=ax[1]) # use the built-in show() >>> plt.show() diff --git a/docs/source/guides/examples/plot/show_section.rst b/docs/source/guides/examples/plot/show_section.rst index 5df8fcbf..98d47f77 100644 --- a/docs/source/guides/examples/plot/show_section.rst +++ b/docs/source/guides/examples/plot/show_section.rst @@ -6,8 +6,7 @@ View a section slice :context: close-figs >>> golfcube = dm.sample_data.golf() - >>> golfstrat = dm.cube.StratigraphyCube.from_DataCube( - ... golfcube, dz=0.1) + >>> golfstrat = dm.cube.StratigraphyCube.from_DataCube(golfcube, dz=0.1) >>> circular = dm.section.CircularSection(golfstrat, radius=2000) You can visualize the data yourself, or use the built-in `show()` method of a `Section`. @@ -17,8 +16,8 @@ You can visualize the data yourself, or use the built-in `show()` method of a `S :context: >>> fig, ax = plt.subplots(1, 2, figsize=(7, 3)) - >>> ax[0].imshow(circular['velocity']) # display directly - >>> circular.show('velocity', ax=ax[1]) # use the built-in show() + >>> ax[0].imshow(circular["velocity"]) # display directly + >>> circular.show("velocity", ax=ax[1]) # use the built-in show() >>> plt.show() .. hint:: diff --git a/docs/source/guides/examples/plot/simple_movie.rst b/docs/source/guides/examples/plot/simple_movie.rst index b70fcb85..f8102222 100644 --- a/docs/source/guides/examples/plot/simple_movie.rst +++ b/docs/source/guides/examples/plot/simple_movie.rst @@ -50,10 +50,9 @@ Then, make the animation with matplotlib's `FuncAnimation`. .. code:: anim = animation.FuncAnimation( - fig, update_field, - frames=golf.shape[0]-1, - interval=20) - anim.save('simple_movie.gif', fps=30) + fig, update_field, frames=golf.shape[0] - 1, interval=20 + ) + anim.save("simple_movie.gif", fps=30) plt.show() diff --git a/docs/source/guides/subject_guides/mask.rst b/docs/source/guides/subject_guides/mask.rst index 9df3bdc3..f9c5685a 100644 --- a/docs/source/guides/subject_guides/mask.rst +++ b/docs/source/guides/subject_guides/mask.rst @@ -21,14 +21,14 @@ For example: >>> golfcube = dm.sample_data.golf() >>> OAP = dm.plan.OpeningAnglePlanform.from_elevation_data( - ... golfcube['eta'][-1, :, :], - ... elevation_threshold=0) + ... golfcube["eta"][-1, :, :], elevation_threshold=0 + ... ) >>> lm = dm.mask.LandMask.from_Planform(OAP) >>> sm = dm.mask.ShorelineMask.from_Planform(OAP) >>> fig, ax = plt.subplots(2, 2) - >>> golfcube.quick_show('eta', idx=-1, ax=ax[0, 0]) + >>> golfcube.quick_show("eta", idx=-1, ax=ax[0, 0]) >>> OAP.show(ax=ax[0, 1]) >>> lm.show(ax=ax[1, 0]) >>> sm.show(ax=ax[1, 1]) @@ -45,12 +45,8 @@ Sometimes it is helpful to :meth:`trim a mask <~deltametrics.mask.BaseMask.trim_ >>> golfcube = dm.sample_data.golf() - >>> m0 = dm.mask.LandMask( - ... golfcube['eta'][-1, :, :], - ... elevation_threshold=0) - >>> m1 = dm.mask.LandMask( - ... golfcube['eta'][-1, :, :], - ... elevation_threshold=0) + >>> m0 = dm.mask.LandMask(golfcube["eta"][-1, :, :], elevation_threshold=0) + >>> m1 = dm.mask.LandMask(golfcube["eta"][-1, :, :], elevation_threshold=0) >>> # trim one of the masks >>> m1.trim_mask(length=3) diff --git a/docs/source/guides/subject_guides/mobility.rst b/docs/source/guides/subject_guides/mobility.rst index 469f2d39..3de6144c 100644 --- a/docs/source/guides/subject_guides/mobility.rst +++ b/docs/source/guides/subject_guides/mobility.rst @@ -32,11 +32,18 @@ sections of the documentation. >>> landmask_list = [] >>> for i in range(50, 60): - ... landmask_list.append(dm.mask.LandMask( - ... golfcube['eta'][i, ...], elevation_threshold=0)) - ... channelmask_list.append(dm.mask.ChannelMask( - ... golfcube['eta'][i, ...], golfcube['velocity'][i, ...], - ... elevation_threshold=0, flow_threshold=0.3)) + ... landmask_list.append( + ... dm.mask.LandMask(golfcube["eta"][i, ...], elevation_threshold=0) + ... ) + ... channelmask_list.append( + ... dm.mask.ChannelMask( + ... golfcube["eta"][i, ...], + ... golfcube["velocity"][i, ...], + ... elevation_threshold=0, + ... flow_threshold=0.3, + ... ) + ... ) + ... Calculation of mobility metrics ------------------------------- @@ -60,17 +67,17 @@ the documentation. :context: >>> dryfrac = dm.mobility.calculate_channel_decay( - ... channelmask_list, landmask_list, - ... basevalues_idx=[0, 1, 2], window_idx=5) + ... channelmask_list, landmask_list, basevalues_idx=[0, 1, 2], window_idx=5 + ... ) >>> Ophi = dm.mobility.calculate_planform_overlap( - ... channelmask_list, landmask_list, - ... basevalues_idx=[0, 1, 2], window_idx=5) + ... channelmask_list, landmask_list, basevalues_idx=[0, 1, 2], window_idx=5 + ... ) >>> fr = dm.mobility.calculate_reworking_fraction( - ... channelmask_list, landmask_list, - ... basevalues_idx=[0, 1, 2], window_idx=5) + ... channelmask_list, landmask_list, basevalues_idx=[0, 1, 2], window_idx=5 + ... ) >>> PwetA = dm.mobility.calculate_channel_abandonment( - ... channelmask_list, - ... basevalues_idx=[0, 1, 2], window_idx=5) + ... channelmask_list, basevalues_idx=[0, 1, 2], window_idx=5 + ... ) Plotting the mobility metrics ------------------------------ @@ -90,13 +97,13 @@ the list of masks passed to the mobility functions. :context: >>> fig, ax = plt.subplots(2, 2) - >>> dryfrac.plot.line(x='time', ax=ax[0, 0]) - >>> ax[0, 0].set_title('Dry Fraction') - >>> Ophi.plot.line(x='time', ax=ax[0, 1]) - >>> ax[0, 1].set_title('Overlap Values') - >>> fr.plot.line(x='time', ax=ax[1, 0]) - >>> ax[1, 0].set_title('Reworked Fraction') - >>> PwetA.plot.line(x='time', ax=ax[1, 1]) - >>> ax[1, 1].set_title('Abandoned Fraction') + >>> dryfrac.plot.line(x="time", ax=ax[0, 0]) + >>> ax[0, 0].set_title("Dry Fraction") + >>> Ophi.plot.line(x="time", ax=ax[0, 1]) + >>> ax[0, 1].set_title("Overlap Values") + >>> fr.plot.line(x="time", ax=ax[1, 0]) + >>> ax[1, 0].set_title("Reworked Fraction") + >>> PwetA.plot.line(x="time", ax=ax[1, 1]) + >>> ax[1, 1].set_title("Abandoned Fraction") >>> plt.tight_layout() >>> plt.show() diff --git a/docs/source/guides/subject_guides/section.rst b/docs/source/guides/subject_guides/section.rst index 2f25c8ec..a1c0bab0 100644 --- a/docs/source/guides/subject_guides/section.rst +++ b/docs/source/guides/subject_guides/section.rst @@ -20,7 +20,7 @@ The data that make up the section can view the section as a `spacetime` section >>> rcm8cube = dm.sample_data.golf() >>> strike = dm.section.StrikeSection(rcm8cube, distance_idx=10) - >>> strike['velocity'] + >>> strike["velocity"] Size: 81kB array([[0.2 , 0.2 , 0.2 , ..., 0.2 , 0.2 , 0.2 ], [0. , 0. , 0. , ..., 0. , 0. , 0. ], @@ -45,8 +45,8 @@ The same `spacetime` data can be requested in the "preserved" form, where non-pr .. doctest:: - >>> rcm8cube.stratigraphy_from('eta') - >>> strike['velocity'].strat.as_preserved() + >>> rcm8cube.stratigraphy_from("eta") + >>> strike["velocity"].strat.as_preserved() Size: 81kB array([[0.2, 0.2, 0.2, ..., 0.2, 0.2, 0.2], [nan, nan, nan, ..., nan, nan, nan], @@ -72,13 +72,13 @@ We can display the arrays using `matplotlib` to examine the spatiotemporal chang .. code:: >>> fig, ax = plt.subplots(2, 1, sharex=True, figsize=(6, 3.5)) - >>> golfcube.sections['demo'].show('velocity', ax=ax[0]) - >>> ax[0].set_ylabel('$t$ coordinate') + >>> golfcube.sections["demo"].show("velocity", ax=ax[0]) + >>> ax[0].set_ylabel("$t$ coordinate") - >>> golfcube.sections['demo'].show('velocity', data='preserved', ax=ax[1]) - >>> ax[1].set_ylabel('$t$ coordinate') + >>> golfcube.sections["demo"].show("velocity", data="preserved", ax=ax[1]) + >>> ax[1].set_ylabel("$t$ coordinate") - >>> ax[1].set_xlabel('$s$ coordinate') + >>> ax[1].set_xlabel("$s$ coordinate") .. plot:: section/section_lexicon.py diff --git a/docs/source/guides/subject_guides/visualization.rst b/docs/source/guides/subject_guides/visualization.rst index 85c16daa..2c83db4b 100644 --- a/docs/source/guides/subject_guides/visualization.rst +++ b/docs/source/guides/subject_guides/visualization.rst @@ -24,23 +24,29 @@ Section display types .. doctest:: >>> golfcube = dm.sample_data.golf() - >>> golfcube.stratigraphy_from('eta') - >>> golfcube.register_section('demo', dm.section.StrikeSection(distance_idx=10)) - >>> _v = 'velocity' + >>> golfcube.stratigraphy_from("eta") + >>> golfcube.register_section("demo", dm.section.StrikeSection(distance_idx=10)) + >>> _v = "velocity" >>> fig, ax = plt.subplots(3, 2, sharex=True, figsize=(8, 6)) - >>> golfcube.sections['demo'].show(_v, style='lines', - ... data='spacetime', ax=ax[0,0]) #doctest: +SKIP - >>> golfcube.sections['demo'].show(_v, style='shaded', - ... data='spacetime', ax=ax[0,1]) #doctest: +SKIP - >>> golfcube.sections['demo'].show(_v, style='lines', - ... data='preserved', ax=ax[1,0]) #doctest: +SKIP - >>> golfcube.sections['demo'].show(_v, style='shaded', - ... data='preserved', ax=ax[1,1]) #doctest: +SKIP - >>> golfcube.sections['demo'].show(_v, style='lines', - ... data='stratigraphy', ax=ax[2,0]) #doctest: +SKIP - >>> golfcube.sections['demo'].show(_v, style='shaded', - ... data='stratigraphy', ax=ax[2,1]) #doctest: +SKIP - >>> plt.show(block=False) #doctest +SKIP + >>> golfcube.sections["demo"].show( + ... _v, style="lines", data="spacetime", ax=ax[0, 0] + ... ) # doctest: +SKIP + >>> golfcube.sections["demo"].show( + ... _v, style="shaded", data="spacetime", ax=ax[0, 1] + ... ) # doctest: +SKIP + >>> golfcube.sections["demo"].show( + ... _v, style="lines", data="preserved", ax=ax[1, 0] + ... ) # doctest: +SKIP + >>> golfcube.sections["demo"].show( + ... _v, style="shaded", data="preserved", ax=ax[1, 1] + ... ) # doctest: +SKIP + >>> golfcube.sections["demo"].show( + ... _v, style="lines", data="stratigraphy", ax=ax[2, 0] + ... ) # doctest: +SKIP + >>> golfcube.sections["demo"].show( + ... _v, style="shaded", data="stratigraphy", ax=ax[2, 1] + ... ) # doctest: +SKIP + >>> plt.show(block=False) # doctest +SKIP .. plot:: guides/visualization_datacube_section_display_style.py diff --git a/docs/source/guides/userguide.rst b/docs/source/guides/userguide.rst index 4f16c383..3f33dc5a 100644 --- a/docs/source/guides/userguide.rst +++ b/docs/source/guides/userguide.rst @@ -10,11 +10,11 @@ Setting up your coding environment .. testsetup:: * - import deltametrics as dm - import numpy as np - import scipy as sp - import matplotlib.pyplot as plt - import matplotlib.gridspec as gs + >>> import deltametrics as dm + >>> import numpy as np + >>> import scipy as sp + >>> import matplotlib.pyplot as plt + >>> import matplotlib.gridspec as gs All of the documentation in this package assumes that you have imported the DeltaMetrics package as ``dm``: @@ -42,7 +42,7 @@ Connecting to a netCDF file on disk is as simple as: .. code:: - >>> acube = dm.cube.DataCube('/path/to/data/file.nc') + >>> acube = dm.cube.DataCube("/path/to/data/file.nc") .. hint:: @@ -73,11 +73,11 @@ For example, access variables as: .. doctest:: - >>> type(golfcube['eta']) + >>> type(golfcube["eta"]) - >>> type(golfcube['eta'].data) + >>> type(golfcube["eta"].data) - >>> golfcube['eta'].shape + >>> golfcube["eta"].shape (101, 100, 200) Examine a timeseries of bed elevation by taking slices out of the ``eta`` variable; we can slice the underlying data directly with an index, the same as a `numpy` array. @@ -94,17 +94,21 @@ Remember that `time` is ordered along the 0th dimension. >>> # set up indices to slice the cube >>> nt = 5 - >>> t_idxs = np.linspace(0, golfcube.shape[0]-1, num=nt, dtype=int) # linearly interpolate t_idxs - ... + >>> t_idxs = np.linspace( + ... 0, golfcube.shape[0] - 1, num=nt, dtype=int + ... ) # linearly interpolate t_idxs >>> # make the plot >>> fig, ax = plt.subplots(1, nt, figsize=(12, 2)) >>> for i, idx in enumerate(t_idxs): - ... ax[i].imshow(golfcube['eta'][idx, :, :], vmin=-2, vmax=0.5) # show the slice - ... ax[i].set_title('idx = {0}'.format(idx)) + ... ax[i].imshow( + ... golfcube["eta"][idx, :, :], vmin=-2, vmax=0.5 + ... ) # show the slice + ... ax[i].set_title("idx = {0}".format(idx)) ... ax[i].set_xticks([]) ... ax[i].set_yticks([]) - >>> ax[0].set_ylabel('dim1 \n direction') - >>> ax[0].set_xlabel('dim2 direction') + ... + >>> ax[0].set_ylabel("dim1 \n direction") + >>> ax[0].set_xlabel("dim2 direction") >>> plt.show() .. note:: @@ -119,15 +123,13 @@ For example: :context: close-figs >>> # compute the change in bed elevation between the last two intervals above - >>> diff_time = golfcube['eta'][t_idxs[-1], :, :] - golfcube['eta'][t_idxs[-2], :, :] + >>> diff_time = ( + ... golfcube["eta"][t_idxs[-1], :, :] - golfcube["eta"][t_idxs[-2], :, :] + ... ) >>> max_delta = abs(diff_time).max() - ... >>> # make the plot >>> fig, ax = plt.subplots(figsize=(5, 3)) - >>> im = ax.imshow( - ... diff_time, cmap='RdBu', - ... vmax=max_delta, - ... vmin=-max_delta) + >>> im = ax.imshow(diff_time, cmap="RdBu", vmax=max_delta, vmin=-max_delta) >>> cb = dm.plot.append_colorbar(im, ax) # a convenience function >>> plt.show() @@ -149,7 +151,7 @@ The data returned from the planform are an `xarray` `DataArray`, so you can cont >>> final = dm.plan.Planform(golfcube, idx=-1) >>> final.shape (100, 200) - >>> final['eta'] + >>> final["eta"] Size: 80kB array([[ 0.015 , 0.015 , 0.015 , ..., 0.015 , 0.015 , 0.015 ], [ 0.0075, 0.0075, 0.0075, ..., 0.0075, 0.0075, 0.0075], @@ -180,8 +182,8 @@ You can visualize the data yourself, or use the built-in `show()` method of a `P :context: >>> fig, ax = plt.subplots(1, 2, figsize=(7, 3)) - >>> ax[0].imshow(final['velocity']) # display directly - >>> final.show('velocity', ax=ax[1]) # use the built-in show() + >>> ax[0].imshow(final["velocity"]) # display directly + >>> final.show("velocity", ax=ax[1]) # use the built-in show() >>> plt.show() .. hint:: @@ -195,13 +197,13 @@ Use the :meth:`~deltametrics.cube.DataCube.register_planform` method when instan .. doctest:: - >>> golfcube.register_planform('fifty', dm.plan.Planform(idx=50)) + >>> golfcube.register_planform("fifty", dm.plan.Planform(idx=50)) Any registered `Planform` can then be accessed via the :obj:`~deltametrics.cube.DataCube.planforms` attribute of the Cube (returns a `dict`). .. doctest:: - >>> golfcube.planforms['fifty'] + >>> golfcube.planforms["fifty"] @@ -225,7 +227,7 @@ For a data cube, sections are most easily instantiated by the :obj:`~deltametric .. doctest:: - >>> golfcube.register_section('demo', dm.section.StrikeSection(distance_idx=10)) + >>> golfcube.register_section("demo", dm.section.StrikeSection(distance_idx=10)) which creates a section across a constant y-value ``==10``. The path of any `Section` in the ``x-y`` plane can always be accessed via the ``.trace`` attribute. @@ -234,10 +236,13 @@ We can plot the trace on top the the final bed elevation to see where the sectio .. doctest:: >>> fig, ax = plt.subplots() - >>> golfcube.quick_show('eta', idx=-1, ax=ax, ticks=True) - >>> ax.plot(golfcube.sections['demo'].trace[:,0], - ... golfcube.sections['demo'].trace[:,1], 'r--') #doctest: +SKIP - >>> plt.show() #doctest: +SKIP + >>> golfcube.quick_show("eta", idx=-1, ax=ax, ticks=True) + >>> ax.plot( + ... golfcube.sections["demo"].trace[:, 0], + ... golfcube.sections["demo"].trace[:, 1], + ... "r--", + ... ) # doctest: +SKIP + >>> plt.show() # doctest: +SKIP .. plot:: guides/userguide_strikesection_location.py @@ -245,7 +250,7 @@ Any registered section can then be accessed via the :obj:`~deltametrics.cube.Cub .. doctest:: - >>> golfcube.sections['demo'] + >>> golfcube.sections["demo"] Available section types are ``PathSection``, ``StrikeSection``, @@ -255,8 +260,8 @@ are sliced themselves, similarly to the cube. .. doctest:: - >>> golfcube.register_section('demo', dm.section.StrikeSection(distance_idx=10)) - >>> golfcube.sections['demo']['velocity'] + >>> golfcube.register_section("demo", dm.section.StrikeSection(distance_idx=10)) + >>> golfcube.sections["demo"]["velocity"] Size: 81kB array([[0.2 , 0.2 , 0.2 , ..., 0.2 , 0.2 , 0.2 ], [0. , 0. , 0. , ..., 0. , 0. , 0. ], @@ -279,11 +284,11 @@ We can visualize sections: .. doctest:: - >>> fig, ax = plt.subplots(3, 1, sharex=True, figsize=(12,6)) - >>> golfcube.show_section('demo', 'eta', ax=ax[0]) - >>> golfcube.show_section('demo', 'velocity', ax=ax[1]) - >>> golfcube.show_section('demo', 'sandfrac', ax=ax[2]) - >>> plt.show() #doctest: +SKIP + >>> fig, ax = plt.subplots(3, 1, sharex=True, figsize=(12, 6)) + >>> golfcube.show_section("demo", "eta", ax=ax[0]) + >>> golfcube.show_section("demo", "velocity", ax=ax[1]) + >>> golfcube.show_section("demo", "sandfrac", ax=ax[2]) + >>> plt.show() # doctest: +SKIP .. plot:: guides/userguide_three_spacetime_sections.py @@ -293,7 +298,9 @@ You can also create a standalone section, which is not registered to the cube, b .. doctest:: >>> sass = dm.section.StrikeSection(golfcube, distance_idx=10) - >>> np.all(sass['velocity'] == golfcube.sections['demo']['velocity']) #doctest: +SKIP + >>> np.all( + ... sass["velocity"] == golfcube.sections["demo"]["velocity"] + ... ) # doctest: +SKIP True @@ -314,13 +321,13 @@ Compute "quick stratigraphy" as: .. doctest:: - >>> golfcube.stratigraphy_from('eta', dz=0.1) + >>> golfcube.stratigraphy_from("eta", dz=0.1) Now, the ``DataCube`` has knowledge of stratigraphy, which we can further use to visualize preservation within the spacetime, or visualize as an actual stratigraphic slice. .. doctest:: - >>> golfcube.sections['demo']['velocity'].strat.as_preserved() + >>> golfcube.sections["demo"]["velocity"].strat.as_preserved() Size: 81kB array([[0.2, 0.2, 0.2, ..., 0.2, 0.2, 0.2], [nan, nan, nan, ..., nan, nan, nan], @@ -342,10 +349,10 @@ Now, the ``DataCube`` has knowledge of stratigraphy, which we can further use to .. doctest:: >>> fig, ax = plt.subplots(3, 1, sharex=True, figsize=(12, 8)) - >>> golfcube.show_section('demo', 'velocity', ax=ax[0]) - >>> golfcube.show_section('demo', 'velocity', data='preserved', ax=ax[1]) - >>> golfcube.show_section('demo', 'velocity', data='stratigraphy', ax=ax[2]) - >>> plt.show() #doctest: +SKIP + >>> golfcube.show_section("demo", "velocity", ax=ax[0]) + >>> golfcube.show_section("demo", "velocity", data="preserved", ax=ax[1]) + >>> golfcube.show_section("demo", "velocity", data="stratigraphy", ax=ax[2]) + >>> plt.show() # doctest: +SKIP .. plot:: guides/userguide_quick_stratigraphy_sections.py @@ -356,10 +363,12 @@ Quick stratigraphy makes it easy to visualize the behavior of the model across e >>> fig, ax = plt.subplots(5, 1, sharex=True, sharey=True, figsize=(12, 12)) >>> ax = ax.flatten() - >>> for i, var in enumerate(['time', 'eta', 'velocity', 'discharge', 'sandfrac']): - ... golfcube.show_section('demo', var, ax=ax[i], label=True, - ... style='shaded', data='stratigraphy') - >>> plt.show() #doctest: +SKIP + >>> for i, var in enumerate(["time", "eta", "velocity", "discharge", "sandfrac"]): + ... golfcube.show_section( + ... "demo", var, ax=ax[i], label=True, style="shaded", data="stratigraphy" + ... ) + ... + >>> plt.show() # doctest: +SKIP .. plot:: guides/userguide_quick_stratigraphy_all_variables.py @@ -376,7 +385,9 @@ The below figure shows each section type available and the `velocity` spacetime .. doctest:: >>> _strike = dm.section.StrikeSection(golfcube, distance=1200) - >>> _path = dm.section.PathSection(golfcube, path=np.array([[1400, 2000], [2000, 4000], [3000, 6000]])) + >>> _path = dm.section.PathSection( + ... golfcube, path=np.array([[1400, 2000], [2000, 4000], [3000, 6000]]) + ... ) >>> _circ = dm.section.CircularSection(golfcube, radius=2000) >>> _rad = dm.section.RadialSection(golfcube, azimuth=70) @@ -412,10 +423,10 @@ Here’s a simple example to demonstrate how we place data into the stratigraphy .. doctest:: - >>> ets = golfcube['eta'][:, 10, 85] # a "real" slice of the model + >>> ets = golfcube["eta"][:, 10, 85] # a "real" slice of the model >>> fig, ax = plt.subplots(figsize=(8, 4)) >>> dm.plot.show_one_dimensional_trajectory_to_strata(ets, ax=ax, dz=0.25) - >>> plt.show() #doctest: +SKIP + >>> plt.show() # doctest: +SKIP .. plot:: guides/userguide_1d_example.py @@ -435,9 +446,9 @@ Compare the slice from the `golfcube` (left) to the `stratcube` (right): .. doctest:: >>> fig, ax = plt.subplots(1, 2, figsize=(8, 2)) - >>> golfcube.sections['demo'].show('velocity', ax=ax[0]) #doctest: +SKIP - >>> stratcube.sections['demo'].show('velocity', ax=ax[1]) #doctest: +SKIP - >>> plt.show() #doctest: +SKIP + >>> golfcube.sections["demo"].show("velocity", ax=ax[0]) # doctest: +SKIP + >>> stratcube.sections["demo"].show("velocity", ax=ax[1]) # doctest: +SKIP + >>> plt.show() # doctest: +SKIP .. plot:: guides/userguide_compare_slices.py @@ -449,7 +460,7 @@ Let’s add a section at the same location as ``golfcube.sections['demo']``. .. doctest:: - >>> stratcube.register_section('demo', dm.section.StrikeSection(distance_idx=10)) + >>> stratcube.register_section("demo", dm.section.StrikeSection(distance_idx=10)) >>> stratcube.sections {'demo': } @@ -458,10 +469,12 @@ Let's examine the stratigraphy in three different visual styles. .. doctest:: >>> fig, ax = plt.subplots(3, 1, sharex=True, sharey=True, figsize=(12, 8)) - >>> golfcube.sections['demo'].show('time', style='lines', data='stratigraphy', ax=ax[0], label=True) - >>> stratcube.sections['demo'].show('time', ax=ax[1]) - >>> golfcube.sections['demo'].show('time', data='stratigraphy', ax=ax[2]) - >>> plt.show() #doctest: +SKIP + >>> golfcube.sections["demo"].show( + ... "time", style="lines", data="stratigraphy", ax=ax[0], label=True + ... ) + >>> stratcube.sections["demo"].show("time", ax=ax[1]) + >>> golfcube.sections["demo"].show("time", data="stratigraphy", ax=ax[2]) + >>> plt.show() # doctest: +SKIP .. plot:: guides/userguide_three_stratigraphy.py @@ -471,10 +484,12 @@ Similar to the demonstration above, each variable (property) of the underlying c >>> fig, ax = plt.subplots(5, 1, sharex=True, sharey=True, figsize=(12, 12)) >>> ax = ax.flatten() - >>> for i, var in enumerate(['time', 'eta', 'velocity', 'discharge', 'sandfrac']): - ... stratcube.show_section('demo', var, ax=ax[i], label=True, - ... style='shaded', data='stratigraphy') - >>> plt.show() #doctest: +SKIP + >>> for i, var in enumerate(["time", "eta", "velocity", "discharge", "sandfrac"]): + ... stratcube.show_section( + ... "demo", var, ax=ax[i], label=True, style="shaded", data="stratigraphy" + ... ) + ... + >>> plt.show() # doctest: +SKIP .. plot:: guides/userguide_all_vars_stratigraphy.py @@ -487,8 +502,7 @@ Specify `z` as the elevation of the planform slice: :context: reset >>> golfcube = dm.sample_data.golf() - >>> stratcube = dm.cube.StratigraphyCube.from_DataCube( - ... golfcube, dz=0.05) + >>> stratcube = dm.cube.StratigraphyCube.from_DataCube(golfcube, dz=0.05) .. plot:: :include-source: @@ -497,7 +511,7 @@ Specify `z` as the elevation of the planform slice: >>> minus2_slice = dm.plan.Planform(stratcube, z=-2) >>> fig, ax = plt.subplots() - >>> minus2_slice.show('sandfrac', ticks=True, ax=ax) + >>> minus2_slice.show("sandfrac", ticks=True, ax=ax) >>> plt.show() @@ -509,24 +523,30 @@ speed up computations if an array is being accessed over and over. .. code:: - fs = stratcube.export_frozen_variable('sandfrac') + fs = stratcube.export_frozen_variable("sandfrac") fe = stratcube.Z # exported volume does not have coordinate information! fig, ax = plt.subplots(figsize=(10, 2)) - pcm = ax.pcolormesh(np.tile(np.arange(fs.shape[2]), (fs.shape[0], 1)), - fe[:,10,:], fs[:,10,:], shading='auto', - cmap=golfcube.varset['sandfrac'].cmap, - vmin=golfcube.varset['sandfrac'].vmin, - vmax=golfcube.varset['sandfrac'].vmax) + pcm = ax.pcolormesh( + np.tile(np.arange(fs.shape[2]), (fs.shape[0], 1)), + fe[:, 10, :], + fs[:, 10, :], + shading="auto", + cmap=golfcube.varset["sandfrac"].cmap, + vmin=golfcube.varset["sandfrac"].vmin, + vmax=golfcube.varset["sandfrac"].vmax, + ) dm.plot.append_colorbar(pcm, ax) - plt.show() #doctest: +SKIP + plt.show() # doctest: +SKIP Note than you can also bypass the creation of a ``StratigraphyCube``, and just directly obtain a frozen volume with: .. doctest:: - >>> fs, fe = dm.strat.compute_boxy_stratigraphy_volume(golfcube['eta'], golfcube['sandfrac'], dz=0.05) + >>> fs, fe = dm.strat.compute_boxy_stratigraphy_volume( + ... golfcube["eta"], golfcube["sandfrac"], dz=0.05 + ... ) However, this will require recomputing the stratigraphy preservation to create another cube in the future, and because the ``StratigraphyCube`` stores data on disk, the memory footprint is relatively small, and so we recommend just computing the ``StratigraphyCube`` and using the ``export_frozen_variable)`` method. Finally, ``DataCubeVariable`` and ``StratigraphyCubeVariable`` support a ``.as_frozen()`` method themselves. @@ -535,7 +555,9 @@ We should verify that the frozen cubes actually match the underlying data! .. doctest:: - >>> np.all( fs[~np.isnan(fs)] == stratcube['sandfrac'][~np.isnan(stratcube['sandfrac'])] ) #doctest: +SKIP + >>> np.all( + ... fs[~np.isnan(fs)] == stratcube["sandfrac"][~np.isnan(stratcube["sandfrac"])] + ... ) # doctest: +SKIP True The access speed of a frozen volume is **much** faster than a live cube. From c06ad790584be13372929ff5570df7bc911af89b Mon Sep 17 00:00:00 2001 From: mcflugen Date: Fri, 20 Dec 2024 11:59:21 -0700 Subject: [PATCH 3/4] apply black to the sample_data docs --- docs/source/reference/sample_data/index.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/source/reference/sample_data/index.rst b/docs/source/reference/sample_data/index.rst index 0b1111db..210c0ce8 100644 --- a/docs/source/reference/sample_data/index.rst +++ b/docs/source/reference/sample_data/index.rst @@ -51,5 +51,5 @@ Paths to data files .. code:: - >>> dm.sample_data._get_golf_path() - '/deltametrics/golf.zip.unzip/pyDeltaRCM_output.nc' + >>> dm.sample_data._get_golf_path() + '/deltametrics/golf.zip.unzip/pyDeltaRCM_output.nc' From b5c1532a7e7be0c4a537672a9e6724a7b5a680bd Mon Sep 17 00:00:00 2001 From: mcflugen Date: Fri, 20 Dec 2024 12:00:01 -0700 Subject: [PATCH 4/4] run the blackdoc hook --- noxfile.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/noxfile.py b/noxfile.py index 8acc2a1f..66749c59 100644 --- a/noxfile.py +++ b/noxfile.py @@ -55,7 +55,7 @@ def coverage(session: nox.Session) -> None: @nox.session def lint(session: nox.Session) -> None: """Look for lint.""" - skip_hooks = ("blackdoc", "file-contents-sorter") + skip_hooks = ("file-contents-sorter",) session.install("pre-commit") session.run("pre-commit", "run", "--all-files", env={"SKIP": ",".join(skip_hooks)})