From f4914ffd897bd4a18c36c0def224b9a832074c60 Mon Sep 17 00:00:00 2001 From: Ashwin Date: Fri, 3 Nov 2023 13:53:57 +0530 Subject: [PATCH 01/51] added wind reconstruction from vorticity and divergence code --- src/metpy/calc/kinematics.py | 63 ++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/src/metpy/calc/kinematics.py b/src/metpy/calc/kinematics.py index c3d8ac85c69..2be4b4f3f0c 100644 --- a/src/metpy/calc/kinematics.py +++ b/src/metpy/calc/kinematics.py @@ -1433,3 +1433,66 @@ def geospatial_laplacian(f, *, dx=None, dy=None, x_dim=-1, y_dim=-2, meridional_scale=meridional_scale) return divergence(grad_u, grad_y, dx=dx, dy=dy, x_dim=x_dim, y_dim=y_dim, parallel_scale=parallel_scale, meridional_scale=meridional_scale) + +@exporter.export +@parse_grid_arguments +@check_units(vortmask='[speed]',dx='[length]', dy='[length]') +def rotational_wind_from_inversion(vortmask,*,dx,dy): + + dx1 = dx.magnitude + + dy1 = dy.magnitude + + vortmask1 = vortmask.values + + for i in range(x_ll_subset, x_ur_subset): + + + for j in range(y_ur_subset, y_ll_subset): + + iindex[:,:] = i + jindex[:,:] = j + xdiff = (iindex-xindex)*dx1[y_ur:y_ll,x_ll:x_ur] + ydiff = (jindex-yindex)*dy1[y_ur:y_ll,x_ll:x_ur] + rsq = xdiff * xdiff + ydiff * ydiff + upsi[j,i] = np.where(rsq > 0., vortmask1[y_ur:y_ll,x_ll:x_ur]*-1.0*(ydiff/rsq)*dx1[y_ur:y_ll,x_ll:x_ur]*dy1[y_ur:y_ll,x_ll:x_ur], 0.0).sum() + vpsi[j,i] = np.where(rsq > 0., vortmask1[y_ur:y_ll,x_ll:x_ur]*-1.0*(xdiff/rsq)*dx1[y_ur:y_ll,x_ll:x_ur]*dy1[y_ur:y_ll,x_ll:x_ur], 0.0).sum() + + + + + upsi[:,:] = (1/(2*np.pi)) * upsi[:,:] + vpsi[:,:] = (1/(2*np.pi)) * vpsi[:,:] + + return upsi,vpsi + +@exporter.export +@parse_grid_arguments +@check_units(divmask='[speed]',dx='[length]', dy='[length]') +def divergent_wind_from_inversion(divmask,*,dx,dy): + + dx1 = dx.magnitude + + dy1 = dy.magnitude + + divmask1 = divmask.values + + + for i in range(x_ll_subset, x_ur_subset): + + + for j in range(y_ur_subset, y_ll_subset): + + iindex[:,:] = i + jindex[:,:] = j + xdiff = (iindex-xindex)*dx1[y_ur:y_ll,x_ll:x_ur] + ydiff = (jindex-yindex)*dy1[y_ur:y_ll,x_ll:x_ur] + rsq = xdiff * xdiff + ydiff * ydiff + uchi[j,i] = np.where(rsq > 0., divmask1[y_ur:y_ll,x_ll:x_ur]*-1.0*(xdiff/rsq)*dx1[y_ur:y_ll,x_ll:x_ur]*dy1[y_ur:y_ll,x_ll:x_ur], 0.0).sum() + vchi[j,i] = np.where(rsq > 0., divmask1[y_ur:y_ll,x_ll:x_ur]*-1.0*(ydiff/rsq)*dx1[y_ur:y_ll,x_ll:x_ur]*dy1[y_ur:y_ll,x_ll:x_ur], 0.0).sum() + + + + + uchi[:,:] = (1/(2*np.pi)) * uchi[:,:] + vchi[:,:] = (1/(2*np.pi)) * vchi[:,:] From b34c706e7c20a80f90c0579af71d8f04f48ef27a Mon Sep 17 00:00:00 2001 From: Ashwin Date: Fri, 3 Nov 2023 14:33:31 +0530 Subject: [PATCH 02/51] added wind reconstruction from vorticity and divergence code --- logs | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 logs diff --git a/logs b/logs new file mode 100644 index 00000000000..5a6f017ff4d --- /dev/null +++ b/logs @@ -0,0 +1,8 @@ +Obtaining file:///home/winash12/projects/metpy + Installing build dependencies: started + Installing build dependencies: finished with status 'done' + Getting requirements to build wheel: started + Getting requirements to build wheel: finished with status 'done' + Preparing wheel metadata: started + Preparing wheel metadata: finished with status 'done' +ERROR: Package 'MetPy-0.0.post5779-ge149219' requires a different Python: 3.8.10 not in '>=3.9' From 4d2ff005652fe4e25f14b144259f132047cd1b78 Mon Sep 17 00:00:00 2001 From: Ashwin Date: Fri, 3 Nov 2023 14:35:29 +0530 Subject: [PATCH 03/51] added wind reconstruction from vorticity and divergence code --- src/metpy/calc/kinematics.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/metpy/calc/kinematics.py b/src/metpy/calc/kinematics.py index 2be4b4f3f0c..dc9afaa94e5 100644 --- a/src/metpy/calc/kinematics.py +++ b/src/metpy/calc/kinematics.py @@ -1456,7 +1456,7 @@ def rotational_wind_from_inversion(vortmask,*,dx,dy): ydiff = (jindex-yindex)*dy1[y_ur:y_ll,x_ll:x_ur] rsq = xdiff * xdiff + ydiff * ydiff upsi[j,i] = np.where(rsq > 0., vortmask1[y_ur:y_ll,x_ll:x_ur]*-1.0*(ydiff/rsq)*dx1[y_ur:y_ll,x_ll:x_ur]*dy1[y_ur:y_ll,x_ll:x_ur], 0.0).sum() - vpsi[j,i] = np.where(rsq > 0., vortmask1[y_ur:y_ll,x_ll:x_ur]*-1.0*(xdiff/rsq)*dx1[y_ur:y_ll,x_ll:x_ur]*dy1[y_ur:y_ll,x_ll:x_ur], 0.0).sum() + vpsi[j,i] = np.where(rsq > 0., vortmask1[y_ur:y_ll,x_ll:x_ur]*(xdiff/rsq)*dx1[y_ur:y_ll,x_ll:x_ur]*dy1[y_ur:y_ll,x_ll:x_ur], 0.0).sum() From 948815f5ff8ef7b9416cec043d834be01dd70fc5 Mon Sep 17 00:00:00 2001 From: Ashwin Date: Fri, 3 Nov 2023 14:39:18 +0530 Subject: [PATCH 04/51] added wind reconstruction from vorticity and divergence code --- src/metpy/calc/kinematics.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/metpy/calc/kinematics.py b/src/metpy/calc/kinematics.py index dc9afaa94e5..70e88b2d0b0 100644 --- a/src/metpy/calc/kinematics.py +++ b/src/metpy/calc/kinematics.py @@ -1488,8 +1488,8 @@ def divergent_wind_from_inversion(divmask,*,dx,dy): xdiff = (iindex-xindex)*dx1[y_ur:y_ll,x_ll:x_ur] ydiff = (jindex-yindex)*dy1[y_ur:y_ll,x_ll:x_ur] rsq = xdiff * xdiff + ydiff * ydiff - uchi[j,i] = np.where(rsq > 0., divmask1[y_ur:y_ll,x_ll:x_ur]*-1.0*(xdiff/rsq)*dx1[y_ur:y_ll,x_ll:x_ur]*dy1[y_ur:y_ll,x_ll:x_ur], 0.0).sum() - vchi[j,i] = np.where(rsq > 0., divmask1[y_ur:y_ll,x_ll:x_ur]*-1.0*(ydiff/rsq)*dx1[y_ur:y_ll,x_ll:x_ur]*dy1[y_ur:y_ll,x_ll:x_ur], 0.0).sum() + uchi[j,i] = np.where(rsq > 0., divmask1[y_ur:y_ll,x_ll:x_ur]*(xdiff/rsq)*dx1[y_ur:y_ll,x_ll:x_ur]*dy1[y_ur:y_ll,x_ll:x_ur], 0.0).sum() + vchi[j,i] = np.where(rsq > 0., divmask1[y_ur:y_ll,x_ll:x_ur]*(ydiff/rsq)*dx1[y_ur:y_ll,x_ll:x_ur]*dy1[y_ur:y_ll,x_ll:x_ur], 0.0).sum() From 47f1599a7c945c22ab5c8fd73e4cefba7507998a Mon Sep 17 00:00:00 2001 From: Ashwin Date: Fri, 3 Nov 2023 15:41:46 +0530 Subject: [PATCH 05/51] added wind reconstruction from vorticity and divergence code --- src/metpy/calc/kinematics.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/metpy/calc/kinematics.py b/src/metpy/calc/kinematics.py index 70e88b2d0b0..dbed986305d 100644 --- a/src/metpy/calc/kinematics.py +++ b/src/metpy/calc/kinematics.py @@ -1496,3 +1496,5 @@ def divergent_wind_from_inversion(divmask,*,dx,dy): uchi[:,:] = (1/(2*np.pi)) * uchi[:,:] vchi[:,:] = (1/(2*np.pi)) * vchi[:,:] + + return uchi,vchi From 3e6f96d4b35362c7ac3af38db7f6ca0c0b4ac741 Mon Sep 17 00:00:00 2001 From: Ashwin Date: Wed, 8 Nov 2023 16:25:32 +0530 Subject: [PATCH 06/51] added code for wind field reconstruction from vorticity and divergence --- src/metpy/calc/kinematics.py | 54 ++++++++++++++++++++++++++++++++++-- 1 file changed, 51 insertions(+), 3 deletions(-) diff --git a/src/metpy/calc/kinematics.py b/src/metpy/calc/kinematics.py index dbed986305d..d72606ba4ba 100644 --- a/src/metpy/calc/kinematics.py +++ b/src/metpy/calc/kinematics.py @@ -1437,8 +1437,31 @@ def geospatial_laplacian(f, *, dx=None, dy=None, x_dim=-1, y_dim=-2, @exporter.export @parse_grid_arguments @check_units(vortmask='[speed]',dx='[length]', dy='[length]') -def rotational_wind_from_inversion(vortmask,*,dx,dy): - +def rotational_wind_from_inversion(vortmask,*,dx,dy,x_ll_subset,x_ur_subset, + y_ll_subset,y_ur_subset,x_ll,x_ur,y_ll,y_ur): + r"""Calculate reconstructed rotational wind field from vorticity + vortmask : 'xarray DataArray' subset of the original vorticity for the entire globe + dx : `pint.Quantity`,required + The grid spacing(s) in the x-direction. If an array, there should be one item less than + the size of `u` along the applicable axis. Optional if `xarray.DataArray` with + latitude/longitude coordinates used as input. Also optional if one-dimensional + longitude and latitude arguments are given for your data on a non-projected grid. + Keyword-only argument. + dy : `pint.Quantity`, required + The grid spacing(s) in the y-direction. If an array, there should be one item less than + the size of `u` along the applicable axis. Optional if `xarray.DataArray` with + latitude/longitude coordinates used as input. Also optional if one-dimensional + longitude and latitude arguments are given for your data on a non-projected grid. + Keyword-only argument. + x_ll_subset : int, required lower left longitude index of the outer bounding box + X_ur_subset : int, required upper right longitude index of the outer bounding box + y_ll_subset : int, required lower left latitude index of the outer bounding box + y_ur_subset : int, required upper right latitude index of the outer bounding box + x_ll : int, required lower left longitude index of the inner bounding box + X_ur : int, required upper right longitude index of the inner bounding box + y_ll : int, required lower left latitude index of the inner bounding box + y_ur : int, required upper right latitude index of the inner bounding box + """ dx1 = dx.magnitude dy1 = dy.magnitude @@ -1469,7 +1492,32 @@ def rotational_wind_from_inversion(vortmask,*,dx,dy): @exporter.export @parse_grid_arguments @check_units(divmask='[speed]',dx='[length]', dy='[length]') -def divergent_wind_from_inversion(divmask,*,dx,dy): +def divergent_wind_from_inversion(divmask,*,dx,dy,x_ll_subset,x_ur_subset, + y_ll_subset,y_ur_subset,x_ll,x_ur,y_ll,y_ur): + + r"""Calculate reconstructed rotational wind field from vorticity + divmask : 'xarray DataArray' subset of the original vorticity for the entire globe + dx : `pint.Quantity`,required + The grid spacing(s) in the x-direction. If an array, there should be one item less than + the size of `u` along the applicable axis. Optional if `xarray.DataArray` with + latitude/longitude coordinates used as input. Also optional if one-dimensional + longitude and latitude arguments are given for your data on a non-projected grid. + Keyword-only argument. + dy : `pint.Quantity`, required + The grid spacing(s) in the y-direction. If an array, there should be one item less than + the size of `u` along the applicable axis. Optional if `xarray.DataArray` with + latitude/longitude coordinates used as input. Also optional if one-dimensional + longitude and latitude arguments are given for your data on a non-projected grid. + Keyword-only argument. + x_ll_subset : int, required lower left longitude index of the outer bounding box + X_ur_subset : int, required upper right longitude index of the outer bounding box + y_ll_subset : int, required lower left latitude index of the outer bounding box + y_ur_subset : int, required upper right latitude index of the outer bounding box + x_ll : int, required lower left longitude index of the inner bounding box + X_ur : int, required upper right longitude index of the inner bounding box + y_ll : int, required lower left latitude index of the inner bounding box + y_ur : int, required upper right latitude index of the inner bounding box + """ dx1 = dx.magnitude From 48450743248041458ff203fb27723850d7482430 Mon Sep 17 00:00:00 2001 From: Ashwin Date: Thu, 9 Nov 2023 10:36:34 +0530 Subject: [PATCH 07/51] changed code comments --- src/metpy/calc/kinematics.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/metpy/calc/kinematics.py b/src/metpy/calc/kinematics.py index d72606ba4ba..1e7c202c093 100644 --- a/src/metpy/calc/kinematics.py +++ b/src/metpy/calc/kinematics.py @@ -1495,7 +1495,7 @@ def rotational_wind_from_inversion(vortmask,*,dx,dy,x_ll_subset,x_ur_subset, def divergent_wind_from_inversion(divmask,*,dx,dy,x_ll_subset,x_ur_subset, y_ll_subset,y_ur_subset,x_ll,x_ur,y_ll,y_ur): - r"""Calculate reconstructed rotational wind field from vorticity + r"""Calculate reconstructed divergent wind field from divergence divmask : 'xarray DataArray' subset of the original vorticity for the entire globe dx : `pint.Quantity`,required The grid spacing(s) in the x-direction. If an array, there should be one item less than From 2eac3f3380a6eb357f5b61133ab5579d65ea7ff2 Mon Sep 17 00:00:00 2001 From: Ashwin Date: Thu, 9 Nov 2023 17:41:04 +0530 Subject: [PATCH 08/51] removed all PEP8 messages --- src/metpy/calc/kinematics.py | 84 ++++++++++++++++-------------------- 1 file changed, 37 insertions(+), 47 deletions(-) diff --git a/src/metpy/calc/kinematics.py b/src/metpy/calc/kinematics.py index 1e7c202c093..ac9edbdba10 100644 --- a/src/metpy/calc/kinematics.py +++ b/src/metpy/calc/kinematics.py @@ -1434,13 +1434,14 @@ def geospatial_laplacian(f, *, dx=None, dy=None, x_dim=-1, y_dim=-2, return divergence(grad_u, grad_y, dx=dx, dy=dy, x_dim=x_dim, y_dim=y_dim, parallel_scale=parallel_scale, meridional_scale=meridional_scale) + @exporter.export @parse_grid_arguments -@check_units(vortmask='[speed]',dx='[length]', dy='[length]') -def rotational_wind_from_inversion(vortmask,*,dx,dy,x_ll_subset,x_ur_subset, - y_ll_subset,y_ur_subset,x_ll,x_ur,y_ll,y_ur): +@check_units(vortmask='[speed]', dx='[length]', dy='[length]') +def rotational_wind_from_inversion(vortmask, *, dx, dy, x_ll_subset, x_ur_subset, + y_ll_subset, y_ur_subset, x_ll, x_ur, y_ll, y_ur): r"""Calculate reconstructed rotational wind field from vorticity - vortmask : 'xarray DataArray' subset of the original vorticity for the entire globe + vortmask : 'xarray DataArray' subset of the original vorticity for the entire globe dx : `pint.Quantity`,required The grid spacing(s) in the x-direction. If an array, there should be one item less than the size of `u` along the applicable axis. Optional if `xarray.DataArray` with @@ -1463,40 +1464,35 @@ def rotational_wind_from_inversion(vortmask,*,dx,dy,x_ll_subset,x_ur_subset, y_ur : int, required upper right latitude index of the inner bounding box """ dx1 = dx.magnitude - dy1 = dy.magnitude - vortmask1 = vortmask.values - for i in range(x_ll_subset, x_ur_subset): - - - for j in range(y_ur_subset, y_ll_subset): - - iindex[:,:] = i - jindex[:,:] = j - xdiff = (iindex-xindex)*dx1[y_ur:y_ll,x_ll:x_ur] - ydiff = (jindex-yindex)*dy1[y_ur:y_ll,x_ll:x_ur] + for j in range(y_ur_subset, y_ll_subset): + iindex[:, :] = i + jindex[:, :] = j + xdiff = (iindex - xindex) * dx1[y_ur:y_ll, x_ll:x_ur] + ydiff = (jindex - yindex) * dy1[y_ur:y_ll, x_ll:x_ur] rsq = xdiff * xdiff + ydiff * ydiff - upsi[j,i] = np.where(rsq > 0., vortmask1[y_ur:y_ll,x_ll:x_ur]*-1.0*(ydiff/rsq)*dx1[y_ur:y_ll,x_ll:x_ur]*dy1[y_ur:y_ll,x_ll:x_ur], 0.0).sum() - vpsi[j,i] = np.where(rsq > 0., vortmask1[y_ur:y_ll,x_ll:x_ur]*(xdiff/rsq)*dx1[y_ur:y_ll,x_ll:x_ur]*dy1[y_ur:y_ll,x_ll:x_ur], 0.0).sum() - - - + upsi[j, i] = np.where(rsq > 0., vortmask1[y_ur:y_ll, x_ll:x_ur] * -1.0 * ( + ydiff / rsq) * dx1[y_ur:y_ll, x_ll:x_ur] * dy1[y_ur:y_ll, + x_ll:x_ur], 0.0).sum() + vpsi[j, i] = np.where(rsq > 0., vortmask1[y_ur:y_ll, x_ll:x_ur] * ( + xdiff / rsq) * dx1[y_ur:y_ll, x_ll:x_ur] * dy1[y_ur:y_ll, + x_ll:x_ur], 0.0).sum() + upsi[:, :] = (1 / (2 * np.pi)) * upsi[:, :] + vpsi[:, :] = (1 / (2 * np.pi)) * vpsi[:, :] - upsi[:,:] = (1/(2*np.pi)) * upsi[:,:] - vpsi[:,:] = (1/(2*np.pi)) * vpsi[:,:] + return upsi, vpsi - return upsi,vpsi @exporter.export @parse_grid_arguments -@check_units(divmask='[speed]',dx='[length]', dy='[length]') -def divergent_wind_from_inversion(divmask,*,dx,dy,x_ll_subset,x_ur_subset, - y_ll_subset,y_ur_subset,x_ll,x_ur,y_ll,y_ur): +@check_units(divmask='[speed]', dx='[length]', dy='[length]') +def divergent_wind_from_inversion(divmask, *, dx, dy, x_ll_subset, x_ur_subset, + y_ll_subset, y_ur_subset, x_ll, x_ur, y_ll, y_ur): r"""Calculate reconstructed divergent wind field from divergence - divmask : 'xarray DataArray' subset of the original vorticity for the entire globe + divmask : 'xarray DataArray' subset of the original vorticity for the entire globe dx : `pint.Quantity`,required The grid spacing(s) in the x-direction. If an array, there should be one item less than the size of `u` along the applicable axis. Optional if `xarray.DataArray` with @@ -1520,29 +1516,23 @@ def divergent_wind_from_inversion(divmask,*,dx,dy,x_ll_subset,x_ur_subset, """ dx1 = dx.magnitude - dy1 = dy.magnitude - divmask1 = divmask.values - - for i in range(x_ll_subset, x_ur_subset): - - - for j in range(y_ur_subset, y_ll_subset): - - iindex[:,:] = i - jindex[:,:] = j - xdiff = (iindex-xindex)*dx1[y_ur:y_ll,x_ll:x_ur] - ydiff = (jindex-yindex)*dy1[y_ur:y_ll,x_ll:x_ur] + for j in range(y_ur_subset, y_ll_subset): + iindex[:, :] = i + jindex[:, :] = j + xdiff = (iindex - xindex) * dx1[y_ur:y_ll, x_ll:x_ur] + ydiff = (jindex - yindex) * dy1[y_ur:y_ll, x_ll:x_ur] rsq = xdiff * xdiff + ydiff * ydiff - uchi[j,i] = np.where(rsq > 0., divmask1[y_ur:y_ll,x_ll:x_ur]*(xdiff/rsq)*dx1[y_ur:y_ll,x_ll:x_ur]*dy1[y_ur:y_ll,x_ll:x_ur], 0.0).sum() - vchi[j,i] = np.where(rsq > 0., divmask1[y_ur:y_ll,x_ll:x_ur]*(ydiff/rsq)*dx1[y_ur:y_ll,x_ll:x_ur]*dy1[y_ur:y_ll,x_ll:x_ur], 0.0).sum() - - - + uchi[j, i] = np.where(rsq > 0., divmask1[y_ur:y_ll, x_ll:x_ur] * ( + xdiff / rsq) * dx1[y_ur:y_ll, x_ll:x_ur] * dy1[y_ur:y_ll, + x_ll:x_ur], 0.0).sum() + vchi[j, i] = np.where(rsq > 0., divmask1[y_ur:y_ll, x_ll:x_ur] * ( + ydiff / rsq) * dx1[y_ur:y_ll, x_ll:x_ur] * dy1[y_ur:y_ll, + x_ll:x_ur], 0.0).sum() - uchi[:,:] = (1/(2*np.pi)) * uchi[:,:] - vchi[:,:] = (1/(2*np.pi)) * vchi[:,:] + uchi[:, :] = (1 / (2 * np.pi)) * uchi[:, :] + vchi[:, :] = (1 / (2 * np.pi)) * vchi[:, :] - return uchi,vchi + return uchi, vchi From cfd99c267bab64d28e08ccae2ff9836fd583aee1 Mon Sep 17 00:00:00 2001 From: Ashwin Date: Mon, 11 Dec 2023 10:20:13 +0530 Subject: [PATCH 09/51] modified the doc file metpy.calc.rst --- docs/_templates/overrides/metpy.calc.rst | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/_templates/overrides/metpy.calc.rst b/docs/_templates/overrides/metpy.calc.rst index c5920a81505..d7cc3d68db8 100644 --- a/docs/_templates/overrides/metpy.calc.rst +++ b/docs/_templates/overrides/metpy.calc.rst @@ -126,7 +126,8 @@ Dynamic/Kinematic wind_components wind_direction wind_speed - + rotational_wind_from_inversion + divergent_wind_from_inversion Boundary Layer/Turbulence ------------------------- From a09328af3e903fd45b63615b33639ec790521975 Mon Sep 17 00:00:00 2001 From: Ashwin Date: Mon, 11 Dec 2023 10:27:15 +0530 Subject: [PATCH 10/51] modified kinematics.py to add extra line --- src/metpy/calc/kinematics.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/metpy/calc/kinematics.py b/src/metpy/calc/kinematics.py index ac9edbdba10..816b3246f54 100644 --- a/src/metpy/calc/kinematics.py +++ b/src/metpy/calc/kinematics.py @@ -1441,6 +1441,9 @@ def geospatial_laplacian(f, *, dx=None, dy=None, x_dim=-1, y_dim=-2, def rotational_wind_from_inversion(vortmask, *, dx, dy, x_ll_subset, x_ur_subset, y_ll_subset, y_ur_subset, x_ll, x_ur, y_ll, y_ur): r"""Calculate reconstructed rotational wind field from vorticity + + Parameters + ---------- vortmask : 'xarray DataArray' subset of the original vorticity for the entire globe dx : `pint.Quantity`,required The grid spacing(s) in the x-direction. If an array, there should be one item less than @@ -1492,6 +1495,9 @@ def divergent_wind_from_inversion(divmask, *, dx, dy, x_ll_subset, x_ur_subset, y_ll_subset, y_ur_subset, x_ll, x_ur, y_ll, y_ur): r"""Calculate reconstructed divergent wind field from divergence + + Parameters + ---------- divmask : 'xarray DataArray' subset of the original vorticity for the entire globe dx : `pint.Quantity`,required The grid spacing(s) in the x-direction. If an array, there should be one item less than From 2386ae313608c47a72b80cfcd5195afca0b8de24 Mon Sep 17 00:00:00 2001 From: Ashwin Date: Wed, 27 Mar 2024 14:45:57 +0530 Subject: [PATCH 11/51] making few changes --- src/metpy/calc/kinematics.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/metpy/calc/kinematics.py b/src/metpy/calc/kinematics.py index 816b3246f54..cda0ec721a1 100644 --- a/src/metpy/calc/kinematics.py +++ b/src/metpy/calc/kinematics.py @@ -1440,7 +1440,7 @@ def geospatial_laplacian(f, *, dx=None, dy=None, x_dim=-1, y_dim=-2, @check_units(vortmask='[speed]', dx='[length]', dy='[length]') def rotational_wind_from_inversion(vortmask, *, dx, dy, x_ll_subset, x_ur_subset, y_ll_subset, y_ur_subset, x_ll, x_ur, y_ll, y_ur): - r"""Calculate reconstructed rotational wind field from vorticity + r"""Calculate reconstructed rotational wind field from vorticity. Parameters ---------- @@ -1494,7 +1494,7 @@ def rotational_wind_from_inversion(vortmask, *, dx, dy, x_ll_subset, x_ur_subset def divergent_wind_from_inversion(divmask, *, dx, dy, x_ll_subset, x_ur_subset, y_ll_subset, y_ur_subset, x_ll, x_ur, y_ll, y_ur): - r"""Calculate reconstructed divergent wind field from divergence + r"""Calculate reconstructed divergent wind field from divergence. Parameters ---------- From dee7361fd499d41696032362734d0f5a60cb01ec Mon Sep 17 00:00:00 2001 From: Ashwin Date: Fri, 5 Apr 2024 07:32:51 +0530 Subject: [PATCH 12/51] modified tools.py to include 2 functions --- src/metpy/calc/tools.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/src/metpy/calc/tools.py b/src/metpy/calc/tools.py index 16e2c8c2da2..c6979c1f181 100644 --- a/src/metpy/calc/tools.py +++ b/src/metpy/calc/tools.py @@ -7,6 +7,7 @@ from inspect import Parameter, signature from operator import itemgetter +from dataclasses import dataclass import numpy as np from numpy.core.numeric import normalize_axis_index import numpy.ma as ma @@ -1922,3 +1923,32 @@ def _remove_nans(*variables): for v in variables: ret.append(v[~mask]) return ret + + +@exporter.export +def bounding_box_mask(data_array, min_lat, max_lat, min_lon, max_lon): + """ Returns a bounding box within the specified coordinates + """ + mask = ((data_array.latitude <= max_lat) & (data_array.latitude >= min_lat) + & (data_array.longitude <= max_lon) & (data_array.longitude >= min_lon)) + data_mask = data_array.where(mask) + + data_mask = data_mask.fillna(0.0) + return data_mask + + +@exporter.export +def find_bounding_box_indices(data_mask, min_lat, max_lat, min_lon, max_lon): + + @dataclass + class BoundingBoxIndices: + x_ll: int = None + x_ur: int = None + y_ll: int = None + y_ur: int = None + x_ll = list(data_mask.longitude.values).index(min_lon) + x_ur = list(data_mask.longitude.values).index(max_lon) + y_ll = list(data_mask.latitude.values).index(min_lat) + y_ur = list(data_tmask.latitude.values).index(max_lat) + bounding_box_indices = BoundingBoxIndices(x_ll, x_ur, y_ll, y_ur) + return bounding_box_indices From 598b4d8d8a99220b236ee0c76b20118984d49779 Mon Sep 17 00:00:00 2001 From: Ashwin Date: Fri, 5 Apr 2024 14:48:03 +0530 Subject: [PATCH 13/51] final code adjustments --- src/metpy/calc/kinematics.py | 45 ++++++++++++++++++++++++++---------- src/metpy/calc/tools.py | 27 ++++++++++++++++++++-- 2 files changed, 58 insertions(+), 14 deletions(-) diff --git a/src/metpy/calc/kinematics.py b/src/metpy/calc/kinematics.py index cda0ec721a1..f9aa08096ef 100644 --- a/src/metpy/calc/kinematics.py +++ b/src/metpy/calc/kinematics.py @@ -3,10 +3,10 @@ # SPDX-License-Identifier: BSD-3-Clause """Contains calculation of kinematic parameters (e.g. divergence or vorticity).""" import numpy as np - +from dataclasses import dataclass from . import coriolis_parameter -from .tools import (first_derivative, geospatial_gradient, get_layer_heights, - parse_grid_arguments, vector_derivative) +from .tools import (first_derivative, geospatial_gradient, get_vectorized_array_indices, + get_layer_heights, parse_grid_arguments, vector_derivative) from .. import constants as mpconsts from ..package_tools import Exporter from ..units import check_units, units @@ -1438,8 +1438,7 @@ def geospatial_laplacian(f, *, dx=None, dy=None, x_dim=-1, y_dim=-2, @exporter.export @parse_grid_arguments @check_units(vortmask='[speed]', dx='[length]', dy='[length]') -def rotational_wind_from_inversion(vortmask, *, dx, dy, x_ll_subset, x_ur_subset, - y_ll_subset, y_ur_subset, x_ll, x_ur, y_ll, y_ur): +def rotational_wind_from_inversion(vortmask, *, dx, dy, o_bb_indices, i_bb_indices): r"""Calculate reconstructed rotational wind field from vorticity. Parameters @@ -1466,11 +1465,23 @@ def rotational_wind_from_inversion(vortmask, *, dx, dy, x_ll_subset, x_ur_subset y_ll : int, required lower left latitude index of the inner bounding box y_ur : int, required upper right latitude index of the inner bounding box """ + upsi = xarray.zeros_like(vortmask) + vpsi = xarray.zeros_like(vortmask) dx1 = dx.magnitude dy1 = dy.magnitude + [iindex, jindex, xindex, yindex] = get_vectorized_array_indices(o_bb_indices, + i_bb_indices) + o_x_ll = o_bb_indices.x_ll + o_x_ur = o_bb_indices.x_ur + o_y_ll = o_bb_indices.y_ll + o_y_ur = o_bb.indices.y_ur + x_ll = i_bb_indices.x_ll + x_ur = i_bb_indices.x_ur + y_ll = i_bb_indices.y_ll + y_ur = i_bb_indices.y_ur vortmask1 = vortmask.values - for i in range(x_ll_subset, x_ur_subset): - for j in range(y_ur_subset, y_ll_subset): + for i in range(o_x_ll, o_x_ur): + for j in range(o_y_ur, o_y_ll): iindex[:, :] = i jindex[:, :] = j xdiff = (iindex - xindex) * dx1[y_ur:y_ll, x_ll:x_ur] @@ -1491,8 +1502,7 @@ def rotational_wind_from_inversion(vortmask, *, dx, dy, x_ll_subset, x_ur_subset @exporter.export @parse_grid_arguments @check_units(divmask='[speed]', dx='[length]', dy='[length]') -def divergent_wind_from_inversion(divmask, *, dx, dy, x_ll_subset, x_ur_subset, - y_ll_subset, y_ur_subset, x_ll, x_ur, y_ll, y_ur): +def divergent_wind_from_inversion(divmask, *, dx, dy, o_bb_indices, i_bb_indices): r"""Calculate reconstructed divergent wind field from divergence. @@ -1520,12 +1530,23 @@ def divergent_wind_from_inversion(divmask, *, dx, dy, x_ll_subset, x_ur_subset, y_ll : int, required lower left latitude index of the inner bounding box y_ur : int, required upper right latitude index of the inner bounding box """ - + uchi = xarray.zeros_like(divmask) + vchi = xarray.zeros_like(divmask) dx1 = dx.magnitude dy1 = dy.magnitude divmask1 = divmask.values - for i in range(x_ll_subset, x_ur_subset): - for j in range(y_ur_subset, y_ll_subset): + [iindex, jindex, xindex, yindex] = get_vectorized_array_indices(o_bb_indices, + i_bb_indices) + o_x_ll = o_bb_indices.x_ll + o_x_ur = o_bb_indices.x_ur + o_y_ll = o_bb_indices.y_ll + o_y_ur = o_bb.indices.y_ur + x_ll = i_bb_indices.x_ll + x_ur = i_bb_indices.x_ur + y_ll = i_bb_indices.y_ll + y_ur = i_bb_indices.y_ur + for i in range(o_x_ll, o_x_ur): + for j in range(o_y_ur, o_y_ll): iindex[:, :] = i jindex[:, :] = j xdiff = (iindex - xindex) * dx1[y_ur:y_ll, x_ll:x_ur] diff --git a/src/metpy/calc/tools.py b/src/metpy/calc/tools.py index c6979c1f181..e1a1220de92 100644 --- a/src/metpy/calc/tools.py +++ b/src/metpy/calc/tools.py @@ -1930,7 +1930,7 @@ def bounding_box_mask(data_array, min_lat, max_lat, min_lon, max_lon): """ Returns a bounding box within the specified coordinates """ mask = ((data_array.latitude <= max_lat) & (data_array.latitude >= min_lat) - & (data_array.longitude <= max_lon) & (data_array.longitude >= min_lon)) + & (data_array.longitude <= max_lon.) & (data_array.longitude >= min_lon)) data_mask = data_array.where(mask) data_mask = data_mask.fillna(0.0) @@ -1949,6 +1949,29 @@ class BoundingBoxIndices: x_ll = list(data_mask.longitude.values).index(min_lon) x_ur = list(data_mask.longitude.values).index(max_lon) y_ll = list(data_mask.latitude.values).index(min_lat) - y_ur = list(data_tmask.latitude.values).index(max_lat) + y_ur = list(data_mask.latitude.values).index(max_lat) bounding_box_indices = BoundingBoxIndices(x_ll, x_ur, y_ll, y_ur) return bounding_box_indices + + +@exporter.export +def get_vectorized_array_indices(o_bb_indices, i_bb_indices): + o_x_ll = o_bounding_box_indices.x_ll + o_x_ur = o_bounding_box_indices.x_ur + o_y_ll = o_bounding_box_indices.y_ll + o_y_ur = o_bounding_box_indices.y_ur + i_x_ll = i_bounding_box_indices.x_ll + i_x_ur = i_bounding_box_indices.x_ur + i_y_ll = i_bounding_box_indices.y_ll + i_y_ur = i_bounding_box_indices.y_ur + i = np.abs(o_x_ll - o_x_ur) + j = np.abs(o_y_ll - o_y_ur) + x = np.abs(i_x_ll - i_x_ur) + y = np.abs(i_y_ll - i_y_ur) + xindex = np.linspace(x_ll, x_ur, num=x * y, endpoint=False, dtype=np.int32) + yindex = np.linspace(y_ur, y_ll, num=y * x, endpoint=False, dtype=np.int32) + xindex = xindex.reshape((y, x), order='F') + yindex = yindex.reshape((y, x), order='C') + iindex = np.zeros((y, x), dtype=np.int32) + jindex = np.zeros((y, x), dtype=np.int32) + return [iindex, jindex, xindex, yindex] From 85c22e1248b6b7eb45cbd189a45ec0d8e3f80c3c Mon Sep 17 00:00:00 2001 From: Ashwin Date: Fri, 5 Apr 2024 14:50:54 +0530 Subject: [PATCH 14/51] made some changes --- pyproject.toml | 0 setup.cfg | 0 2 files changed, 0 insertions(+), 0 deletions(-) mode change 100644 => 100755 pyproject.toml mode change 100644 => 100755 setup.cfg diff --git a/pyproject.toml b/pyproject.toml old mode 100644 new mode 100755 diff --git a/setup.cfg b/setup.cfg old mode 100644 new mode 100755 From ea075330e8bb614f99debefadba1ecbc9444eafe Mon Sep 17 00:00:00 2001 From: winash12 Date: Fri, 5 Apr 2024 15:11:15 +0530 Subject: [PATCH 15/51] Delete logs --- logs | 8 -------- 1 file changed, 8 deletions(-) delete mode 100644 logs diff --git a/logs b/logs deleted file mode 100644 index 5a6f017ff4d..00000000000 --- a/logs +++ /dev/null @@ -1,8 +0,0 @@ -Obtaining file:///home/winash12/projects/metpy - Installing build dependencies: started - Installing build dependencies: finished with status 'done' - Getting requirements to build wheel: started - Getting requirements to build wheel: finished with status 'done' - Preparing wheel metadata: started - Preparing wheel metadata: finished with status 'done' -ERROR: Package 'MetPy-0.0.post5779-ge149219' requires a different Python: 3.8.10 not in '>=3.9' From 0aaae342d5f93f66c5dabfc127e50d93d0c82488 Mon Sep 17 00:00:00 2001 From: Ashwin Date: Tue, 9 Apr 2024 13:51:04 +0530 Subject: [PATCH 16/51] added latest changes for testing --- src/metpy/calc/kinematics.py | 41 ++++++++++++------------------------ src/metpy/calc/tools.py | 25 ++++++++++------------ 2 files changed, 24 insertions(+), 42 deletions(-) diff --git a/src/metpy/calc/kinematics.py b/src/metpy/calc/kinematics.py index f29afe36596..8ee056f0bb1 100644 --- a/src/metpy/calc/kinematics.py +++ b/src/metpy/calc/kinematics.py @@ -3,6 +3,7 @@ # SPDX-License-Identifier: BSD-3-Clause """Contains calculation of kinematic parameters (e.g. divergence or vorticity).""" import numpy as np +import xarray as xa from dataclasses import dataclass from . import coriolis_parameter from .tools import (first_derivative, geospatial_gradient, get_vectorized_array_indices, @@ -1433,9 +1434,7 @@ def geospatial_laplacian(f, *, dx=None, dy=None, x_dim=-1, y_dim=-2, @exporter.export -@parse_grid_arguments -@check_units(vortmask='[speed]', dx='[length]', dy='[length]') -def rotational_wind_from_inversion(vortmask, *, dx, dy, o_bb_indices, i_bb_indices): +def rotational_wind_from_inversion(vortmask, dx, dy, o_bb_indices, i_bb_indices): r"""Calculate reconstructed rotational wind field from vorticity. Parameters @@ -1453,17 +1452,11 @@ def rotational_wind_from_inversion(vortmask, *, dx, dy, o_bb_indices, i_bb_indic latitude/longitude coordinates used as input. Also optional if one-dimensional longitude and latitude arguments are given for your data on a non-projected grid. Keyword-only argument. - x_ll_subset : int, required lower left longitude index of the outer bounding box - X_ur_subset : int, required upper right longitude index of the outer bounding box - y_ll_subset : int, required lower left latitude index of the outer bounding box - y_ur_subset : int, required upper right latitude index of the outer bounding box - x_ll : int, required lower left longitude index of the inner bounding box - X_ur : int, required upper right longitude index of the inner bounding box - y_ll : int, required lower left latitude index of the inner bounding box - y_ur : int, required upper right latitude index of the inner bounding box + o_bb_indices : contains the x and y lower left and upper right indices of the outer bounding box + i_bb_indices : contains the x and y lower left and upper right indices of the inner bounding box """ - upsi = xarray.zeros_like(vortmask) - vpsi = xarray.zeros_like(vortmask) + upsi = xa.zeros_like(vortmask) + vpsi = xa.zeros_like(vortmask) dx1 = dx.magnitude dy1 = dy.magnitude [iindex, jindex, xindex, yindex] = get_vectorized_array_indices(o_bb_indices, @@ -1471,7 +1464,7 @@ def rotational_wind_from_inversion(vortmask, *, dx, dy, o_bb_indices, i_bb_indic o_x_ll = o_bb_indices.x_ll o_x_ur = o_bb_indices.x_ur o_y_ll = o_bb_indices.y_ll - o_y_ur = o_bb.indices.y_ur + o_y_ur = o_bb_indices.y_ur x_ll = i_bb_indices.x_ll x_ur = i_bb_indices.x_ur y_ll = i_bb_indices.y_ll @@ -1497,9 +1490,7 @@ def rotational_wind_from_inversion(vortmask, *, dx, dy, o_bb_indices, i_bb_indic @exporter.export -@parse_grid_arguments -@check_units(divmask='[speed]', dx='[length]', dy='[length]') -def divergent_wind_from_inversion(divmask, *, dx, dy, o_bb_indices, i_bb_indices): +def divergent_wind_from_inversion(divmask, dx, dy, o_bb_indices, i_bb_indices): r"""Calculate reconstructed divergent wind field from divergence. @@ -1518,17 +1509,11 @@ def divergent_wind_from_inversion(divmask, *, dx, dy, o_bb_indices, i_bb_indices latitude/longitude coordinates used as input. Also optional if one-dimensional longitude and latitude arguments are given for your data on a non-projected grid. Keyword-only argument. - x_ll_subset : int, required lower left longitude index of the outer bounding box - X_ur_subset : int, required upper right longitude index of the outer bounding box - y_ll_subset : int, required lower left latitude index of the outer bounding box - y_ur_subset : int, required upper right latitude index of the outer bounding box - x_ll : int, required lower left longitude index of the inner bounding box - X_ur : int, required upper right longitude index of the inner bounding box - y_ll : int, required lower left latitude index of the inner bounding box - y_ur : int, required upper right latitude index of the inner bounding box + o_bb_indices : contains the x and y lower left and upper right indices of the outer bounding box + i_bb_indices : contains the x and y lower left and upper right indices of the inner bounding box """ - uchi = xarray.zeros_like(divmask) - vchi = xarray.zeros_like(divmask) + uchi = xa.zeros_like(divmask) + vchi = xa.zeros_like(divmask) dx1 = dx.magnitude dy1 = dy.magnitude divmask1 = divmask.values @@ -1537,7 +1522,7 @@ def divergent_wind_from_inversion(divmask, *, dx, dy, o_bb_indices, i_bb_indices o_x_ll = o_bb_indices.x_ll o_x_ur = o_bb_indices.x_ur o_y_ll = o_bb_indices.y_ll - o_y_ur = o_bb.indices.y_ur + o_y_ur = o_bb_indices.y_ur x_ll = i_bb_indices.x_ll x_ur = i_bb_indices.x_ur y_ll = i_bb_indices.y_ll diff --git a/src/metpy/calc/tools.py b/src/metpy/calc/tools.py index b09f4fd1515..eccc14eb9ec 100644 --- a/src/metpy/calc/tools.py +++ b/src/metpy/calc/tools.py @@ -1944,9 +1944,8 @@ def bounding_box_mask(data_array, min_lat, max_lat, min_lon, max_lon): """ Returns a bounding box within the specified coordinates """ mask = ((data_array.latitude <= max_lat) & (data_array.latitude >= min_lat) - & (data_array.longitude <= max_lon.) & (data_array.longitude >= min_lon)) + & (data_array.longitude <= max_lon) & (data_array.longitude >= min_lon)) data_mask = data_array.where(mask) - data_mask = data_mask.fillna(0.0) return data_mask @@ -1970,20 +1969,18 @@ class BoundingBoxIndices: @exporter.export def get_vectorized_array_indices(o_bb_indices, i_bb_indices): - o_x_ll = o_bounding_box_indices.x_ll - o_x_ur = o_bounding_box_indices.x_ur - o_y_ll = o_bounding_box_indices.y_ll - o_y_ur = o_bounding_box_indices.y_ur - i_x_ll = i_bounding_box_indices.x_ll - i_x_ur = i_bounding_box_indices.x_ur - i_y_ll = i_bounding_box_indices.y_ll - i_y_ur = i_bounding_box_indices.y_ur - i = np.abs(o_x_ll - o_x_ur) - j = np.abs(o_y_ll - o_y_ur) + o_x_ll = o_bb_indices.x_ll + o_x_ur = o_bb_indices.x_ur + o_y_ll = o_bb_indices.y_ll + o_y_ur = o_bb_indices.y_ur + i_x_ll = i_bb_indices.x_ll + i_x_ur = i_bb_indices.x_ur + i_y_ll = i_bb_indices.y_ll + i_y_ur = i_bb_indices.y_ur x = np.abs(i_x_ll - i_x_ur) y = np.abs(i_y_ll - i_y_ur) - xindex = np.linspace(x_ll, x_ur, num=x * y, endpoint=False, dtype=np.int32) - yindex = np.linspace(y_ur, y_ll, num=y * x, endpoint=False, dtype=np.int32) + xindex = np.linspace(i_x_ll, i_x_ur, num=x * y, endpoint=False, dtype=np.int32) + yindex = np.linspace(i_y_ur, i_y_ll, num=y * x, endpoint=False, dtype=np.int32) xindex = xindex.reshape((y, x), order='F') yindex = yindex.reshape((y, x), order='C') iindex = np.zeros((y, x), dtype=np.int32) From 3ed1dcbb86078f4a03af57387460cb486f1797fa Mon Sep 17 00:00:00 2001 From: Ashwin Date: Tue, 9 Apr 2024 15:36:24 +0530 Subject: [PATCH 17/51] fixed some errors --- src/metpy/calc/kinematics.py | 14 ++++++-------- src/metpy/calc/tools.py | 6 +----- 2 files changed, 7 insertions(+), 13 deletions(-) diff --git a/src/metpy/calc/kinematics.py b/src/metpy/calc/kinematics.py index 8ee056f0bb1..33f6b6e56e7 100644 --- a/src/metpy/calc/kinematics.py +++ b/src/metpy/calc/kinematics.py @@ -1452,15 +1452,14 @@ def rotational_wind_from_inversion(vortmask, dx, dy, o_bb_indices, i_bb_indices) latitude/longitude coordinates used as input. Also optional if one-dimensional longitude and latitude arguments are given for your data on a non-projected grid. Keyword-only argument. - o_bb_indices : contains the x and y lower left and upper right indices of the outer bounding box - i_bb_indices : contains the x and y lower left and upper right indices of the inner bounding box + o_bb_indices : contains the x and y lower left and upper right indices + i_bb_indices : contains the x and y lower left and upper right indices """ upsi = xa.zeros_like(vortmask) vpsi = xa.zeros_like(vortmask) dx1 = dx.magnitude dy1 = dy.magnitude - [iindex, jindex, xindex, yindex] = get_vectorized_array_indices(o_bb_indices, - i_bb_indices) + [iindex, jindex, xindex, yindex] = get_vectorized_array_indices(i_bb_indices) o_x_ll = o_bb_indices.x_ll o_x_ur = o_bb_indices.x_ur o_y_ll = o_bb_indices.y_ll @@ -1509,16 +1508,15 @@ def divergent_wind_from_inversion(divmask, dx, dy, o_bb_indices, i_bb_indices): latitude/longitude coordinates used as input. Also optional if one-dimensional longitude and latitude arguments are given for your data on a non-projected grid. Keyword-only argument. - o_bb_indices : contains the x and y lower left and upper right indices of the outer bounding box - i_bb_indices : contains the x and y lower left and upper right indices of the inner bounding box + o_bb_indices : contains the x and y lower left and upper right indices + i_bb_indices : contains the x and y lower left and upper right indices """ uchi = xa.zeros_like(divmask) vchi = xa.zeros_like(divmask) dx1 = dx.magnitude dy1 = dy.magnitude divmask1 = divmask.values - [iindex, jindex, xindex, yindex] = get_vectorized_array_indices(o_bb_indices, - i_bb_indices) + [iindex, jindex, xindex, yindex] = get_vectorized_array_indices(i_bb_indices) o_x_ll = o_bb_indices.x_ll o_x_ur = o_bb_indices.x_ur o_y_ll = o_bb_indices.y_ll diff --git a/src/metpy/calc/tools.py b/src/metpy/calc/tools.py index eccc14eb9ec..305d149f9e5 100644 --- a/src/metpy/calc/tools.py +++ b/src/metpy/calc/tools.py @@ -1968,11 +1968,7 @@ class BoundingBoxIndices: @exporter.export -def get_vectorized_array_indices(o_bb_indices, i_bb_indices): - o_x_ll = o_bb_indices.x_ll - o_x_ur = o_bb_indices.x_ur - o_y_ll = o_bb_indices.y_ll - o_y_ur = o_bb_indices.y_ur +def get_vectorized_array_indices(i_bb_indices): i_x_ll = i_bb_indices.x_ll i_x_ur = i_bb_indices.x_ur i_y_ll = i_bb_indices.y_ll From a71aac5a97e83487ad748d79a37d8a08aae8e2fa Mon Sep 17 00:00:00 2001 From: Ashwin Date: Tue, 9 Apr 2024 21:07:44 +0530 Subject: [PATCH 18/51] refactored get_vectorized_array_values --- src/metpy/calc/kinematics.py | 8 ++++++-- src/metpy/calc/tools.py | 4 +--- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/src/metpy/calc/kinematics.py b/src/metpy/calc/kinematics.py index 33f6b6e56e7..6e84b730cc9 100644 --- a/src/metpy/calc/kinematics.py +++ b/src/metpy/calc/kinematics.py @@ -1459,7 +1459,9 @@ def rotational_wind_from_inversion(vortmask, dx, dy, o_bb_indices, i_bb_indices) vpsi = xa.zeros_like(vortmask) dx1 = dx.magnitude dy1 = dy.magnitude - [iindex, jindex, xindex, yindex] = get_vectorized_array_indices(i_bb_indices) + [xindex, yindex] = get_vectorized_array_indices(i_bb_indices) + iindex = np.zeros_like(yindex) + jindex = np.zeros_like(yindex) o_x_ll = o_bb_indices.x_ll o_x_ur = o_bb_indices.x_ur o_y_ll = o_bb_indices.y_ll @@ -1516,7 +1518,9 @@ def divergent_wind_from_inversion(divmask, dx, dy, o_bb_indices, i_bb_indices): dx1 = dx.magnitude dy1 = dy.magnitude divmask1 = divmask.values - [iindex, jindex, xindex, yindex] = get_vectorized_array_indices(i_bb_indices) + [xindex, yindex] = get_vectorized_array_indices(i_bb_indices) + iindex = np.zeros_like(yindex) + jindex = np.zeros_like(yindex) o_x_ll = o_bb_indices.x_ll o_x_ur = o_bb_indices.x_ur o_y_ll = o_bb_indices.y_ll diff --git a/src/metpy/calc/tools.py b/src/metpy/calc/tools.py index 305d149f9e5..3a385065da9 100644 --- a/src/metpy/calc/tools.py +++ b/src/metpy/calc/tools.py @@ -1979,6 +1979,4 @@ def get_vectorized_array_indices(i_bb_indices): yindex = np.linspace(i_y_ur, i_y_ll, num=y * x, endpoint=False, dtype=np.int32) xindex = xindex.reshape((y, x), order='F') yindex = yindex.reshape((y, x), order='C') - iindex = np.zeros((y, x), dtype=np.int32) - jindex = np.zeros((y, x), dtype=np.int32) - return [iindex, jindex, xindex, yindex] + return [xindex, yindex] From e9e3d1cb23788fef500cefc65628c3d31fe33ccf Mon Sep 17 00:00:00 2001 From: Ashwin Date: Wed, 10 Apr 2024 07:53:43 +0530 Subject: [PATCH 19/51] added the new methods of tools.py to metpy.calc.rst --- docs/_templates/overrides/metpy.calc.rst | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/_templates/overrides/metpy.calc.rst b/docs/_templates/overrides/metpy.calc.rst index 1e4a7817a81..eb73243699f 100644 --- a/docs/_templates/overrides/metpy.calc.rst +++ b/docs/_templates/overrides/metpy.calc.rst @@ -208,11 +208,14 @@ Other angle_to_direction azimuth_range_to_lat_lon + bounding_box_mask find_bounding_indices + find_bounding_box_indices find_intersections get_layer get_layer_heights get_perturbation + get_vectorized_array_indices isentropic_interpolation isentropic_interpolation_as_dataset nearest_intersection_idx From 6740e510974a0acf027439f951a8dbd6f6cefa14 Mon Sep 17 00:00:00 2001 From: Ashwin Date: Wed, 10 Apr 2024 07:59:24 +0530 Subject: [PATCH 20/51] docs.yml --- .github/workflows/docs.yml | 0 1 file changed, 0 insertions(+), 0 deletions(-) mode change 100644 => 100755 .github/workflows/docs.yml diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml old mode 100644 new mode 100755 From 0a2f72b02d628040111ae621a5789ca8effbcaaf Mon Sep 17 00:00:00 2001 From: Ashwin Date: Wed, 10 Apr 2024 08:41:13 +0530 Subject: [PATCH 21/51] fixed some doc errors --- src/metpy/calc/kinematics.py | 2 -- src/metpy/calc/tools.py | 8 +++++--- 2 files changed, 5 insertions(+), 5 deletions(-) mode change 100644 => 100755 src/metpy/calc/kinematics.py mode change 100644 => 100755 src/metpy/calc/tools.py diff --git a/src/metpy/calc/kinematics.py b/src/metpy/calc/kinematics.py old mode 100644 new mode 100755 index 6e84b730cc9..aeec5110aef --- a/src/metpy/calc/kinematics.py +++ b/src/metpy/calc/kinematics.py @@ -4,7 +4,6 @@ """Contains calculation of kinematic parameters (e.g. divergence or vorticity).""" import numpy as np import xarray as xa -from dataclasses import dataclass from . import coriolis_parameter from .tools import (first_derivative, geospatial_gradient, get_vectorized_array_indices, get_layer_heights, parse_grid_arguments, vector_derivative) @@ -1492,7 +1491,6 @@ def rotational_wind_from_inversion(vortmask, dx, dy, o_bb_indices, i_bb_indices) @exporter.export def divergent_wind_from_inversion(divmask, dx, dy, o_bb_indices, i_bb_indices): - r"""Calculate reconstructed divergent wind field from divergence. Parameters diff --git a/src/metpy/calc/tools.py b/src/metpy/calc/tools.py old mode 100644 new mode 100755 index 3a385065da9..9c67db7082e --- a/src/metpy/calc/tools.py +++ b/src/metpy/calc/tools.py @@ -1941,8 +1941,7 @@ def _remove_nans(*variables): @exporter.export def bounding_box_mask(data_array, min_lat, max_lat, min_lon, max_lon): - """ Returns a bounding box within the specified coordinates - """ + """ This function constructs a bounding box within the specified coordinates""" mask = ((data_array.latitude <= max_lat) & (data_array.latitude >= min_lat) & (data_array.longitude <= max_lon) & (data_array.longitude >= min_lon)) data_mask = data_array.where(mask) @@ -1952,7 +1951,7 @@ def bounding_box_mask(data_array, min_lat, max_lat, min_lon, max_lon): @exporter.export def find_bounding_box_indices(data_mask, min_lat, max_lat, min_lon, max_lon): - + """ This function computes the array indices of a bounding box""" @dataclass class BoundingBoxIndices: x_ll: int = None @@ -1969,6 +1968,9 @@ class BoundingBoxIndices: @exporter.export def get_vectorized_array_indices(i_bb_indices): + """ This function computes the vectorization indices for inner for loop in the + wind field reconstruction method + """ i_x_ll = i_bb_indices.x_ll i_x_ur = i_bb_indices.x_ur i_y_ll = i_bb_indices.y_ll From eb3430e8278a4a4d04a5c011b8bad1ba73ca3d82 Mon Sep 17 00:00:00 2001 From: Ashwin Date: Wed, 10 Apr 2024 09:02:14 +0530 Subject: [PATCH 22/51] fixed docstring errors --- src/metpy/calc/tools.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/metpy/calc/tools.py b/src/metpy/calc/tools.py index 9c67db7082e..6bd75a0f292 100755 --- a/src/metpy/calc/tools.py +++ b/src/metpy/calc/tools.py @@ -1941,7 +1941,10 @@ def _remove_nans(*variables): @exporter.export def bounding_box_mask(data_array, min_lat, max_lat, min_lon, max_lon): - """ This function constructs a bounding box within the specified coordinates""" + """Construct a bounding box mask within the specified coordinates + All values that satisfy the condition below will have 1 in the mask + and others zero + """ mask = ((data_array.latitude <= max_lat) & (data_array.latitude >= min_lat) & (data_array.longitude <= max_lon) & (data_array.longitude >= min_lon)) data_mask = data_array.where(mask) @@ -1951,7 +1954,7 @@ def bounding_box_mask(data_array, min_lat, max_lat, min_lon, max_lon): @exporter.export def find_bounding_box_indices(data_mask, min_lat, max_lat, min_lon, max_lon): - """ This function computes the array indices of a bounding box""" + """Computes the array indices of a bounding box""" @dataclass class BoundingBoxIndices: x_ll: int = None @@ -1968,7 +1971,7 @@ class BoundingBoxIndices: @exporter.export def get_vectorized_array_indices(i_bb_indices): - """ This function computes the vectorization indices for inner for loop in the + """function computes the vectorization indices for inner for loop in the wind field reconstruction method """ i_x_ll = i_bb_indices.x_ll From 31d0a23f434b16a228ac9d160a901d805f12ebeb Mon Sep 17 00:00:00 2001 From: Ashwin Date: Wed, 10 Apr 2024 21:39:19 +0530 Subject: [PATCH 23/51] tried to fix docstring --- src/metpy/calc/tools.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/metpy/calc/tools.py b/src/metpy/calc/tools.py index 6bd75a0f292..e06a909584c 100755 --- a/src/metpy/calc/tools.py +++ b/src/metpy/calc/tools.py @@ -1941,7 +1941,7 @@ def _remove_nans(*variables): @exporter.export def bounding_box_mask(data_array, min_lat, max_lat, min_lon, max_lon): - """Construct a bounding box mask within the specified coordinates + """Construct a bounding box mask within the specified coordinates. All values that satisfy the condition below will have 1 in the mask and others zero """ From 1e01afc3f196fdacbb73f15593e73b760803db9d Mon Sep 17 00:00:00 2001 From: Ashwin Date: Fri, 10 May 2024 06:50:49 +0530 Subject: [PATCH 24/51] made changes --- ci/doc_requirements.txt | 0 ci/extra_requirements.txt | 0 ci/linting_requirements.txt | 0 ci/requirements.txt | 0 docs/conf.py | 0 5 files changed, 0 insertions(+), 0 deletions(-) mode change 100644 => 100755 ci/doc_requirements.txt mode change 100644 => 100755 ci/extra_requirements.txt mode change 100644 => 100755 ci/linting_requirements.txt mode change 100644 => 100755 ci/requirements.txt mode change 100644 => 100755 docs/conf.py diff --git a/ci/doc_requirements.txt b/ci/doc_requirements.txt old mode 100644 new mode 100755 diff --git a/ci/extra_requirements.txt b/ci/extra_requirements.txt old mode 100644 new mode 100755 diff --git a/ci/linting_requirements.txt b/ci/linting_requirements.txt old mode 100644 new mode 100755 diff --git a/ci/requirements.txt b/ci/requirements.txt old mode 100644 new mode 100755 diff --git a/docs/conf.py b/docs/conf.py old mode 100644 new mode 100755 From 4bcca79e42751136c103d32ac82c47f629226ff2 Mon Sep 17 00:00:00 2001 From: Ashwin Date: Fri, 10 May 2024 06:51:18 +0530 Subject: [PATCH 25/51] made changes --- ci/test_requirements.txt | 0 1 file changed, 0 insertions(+), 0 deletions(-) mode change 100644 => 100755 ci/test_requirements.txt diff --git a/ci/test_requirements.txt b/ci/test_requirements.txt old mode 100644 new mode 100755 From 68aa49ef6081f3aef0f5fd75fe91c293f194c79f Mon Sep 17 00:00:00 2001 From: DWesl <22566757+DWesl@users.noreply.github.com> Date: Sat, 11 May 2024 11:56:10 -0400 Subject: [PATCH 26/51] Revert permissions changes. --- .github/workflows/docs.yml | 0 ci/doc_requirements.txt | 0 ci/extra_requirements.txt | 0 ci/linting_requirements.txt | 0 ci/requirements.txt | 0 ci/test_requirements.txt | 0 docs/conf.py | 0 pyproject.toml | 0 setup.cfg | 0 9 files changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 .github/workflows/docs.yml mode change 100755 => 100644 ci/doc_requirements.txt mode change 100755 => 100644 ci/extra_requirements.txt mode change 100755 => 100644 ci/linting_requirements.txt mode change 100755 => 100644 ci/requirements.txt mode change 100755 => 100644 ci/test_requirements.txt mode change 100755 => 100644 docs/conf.py mode change 100755 => 100644 pyproject.toml mode change 100755 => 100644 setup.cfg diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml old mode 100755 new mode 100644 diff --git a/ci/doc_requirements.txt b/ci/doc_requirements.txt old mode 100755 new mode 100644 diff --git a/ci/extra_requirements.txt b/ci/extra_requirements.txt old mode 100755 new mode 100644 diff --git a/ci/linting_requirements.txt b/ci/linting_requirements.txt old mode 100755 new mode 100644 diff --git a/ci/requirements.txt b/ci/requirements.txt old mode 100755 new mode 100644 diff --git a/ci/test_requirements.txt b/ci/test_requirements.txt old mode 100755 new mode 100644 diff --git a/docs/conf.py b/docs/conf.py old mode 100755 new mode 100644 diff --git a/pyproject.toml b/pyproject.toml old mode 100755 new mode 100644 diff --git a/setup.cfg b/setup.cfg old mode 100755 new mode 100644 From 8b5783a4f90fc5e8bcb32daf1bd56cc77cdd064a Mon Sep 17 00:00:00 2001 From: Ashwin Date: Mon, 13 May 2024 15:10:13 +0530 Subject: [PATCH 27/51] new commits i dont know why --- conftest.py | 0 src/metpy/__init__.py | 0 src/metpy/calc/indices.py | 0 src/metpy/calc/thermo.py | 0 src/metpy/calc/tools.py | 2 ++ src/metpy/testing.py | 0 tests/calc/test_thermo.py | 0 tests/plots/test_declarative.py | 0 8 files changed, 2 insertions(+) mode change 100644 => 100755 conftest.py mode change 100644 => 100755 src/metpy/__init__.py mode change 100644 => 100755 src/metpy/calc/indices.py mode change 100644 => 100755 src/metpy/calc/thermo.py mode change 100644 => 100755 src/metpy/testing.py mode change 100644 => 100755 tests/calc/test_thermo.py mode change 100644 => 100755 tests/plots/test_declarative.py diff --git a/conftest.py b/conftest.py old mode 100644 new mode 100755 diff --git a/src/metpy/__init__.py b/src/metpy/__init__.py old mode 100644 new mode 100755 diff --git a/src/metpy/calc/indices.py b/src/metpy/calc/indices.py old mode 100644 new mode 100755 diff --git a/src/metpy/calc/thermo.py b/src/metpy/calc/thermo.py old mode 100644 new mode 100755 diff --git a/src/metpy/calc/tools.py b/src/metpy/calc/tools.py index e06a909584c..9b362f35112 100755 --- a/src/metpy/calc/tools.py +++ b/src/metpy/calc/tools.py @@ -1955,6 +1955,7 @@ def bounding_box_mask(data_array, min_lat, max_lat, min_lon, max_lon): @exporter.export def find_bounding_box_indices(data_mask, min_lat, max_lat, min_lon, max_lon): """Computes the array indices of a bounding box""" + @dataclass class BoundingBoxIndices: x_ll: int = None @@ -1974,6 +1975,7 @@ def get_vectorized_array_indices(i_bb_indices): """function computes the vectorization indices for inner for loop in the wind field reconstruction method """ + i_x_ll = i_bb_indices.x_ll i_x_ur = i_bb_indices.x_ur i_y_ll = i_bb_indices.y_ll diff --git a/src/metpy/testing.py b/src/metpy/testing.py old mode 100644 new mode 100755 diff --git a/tests/calc/test_thermo.py b/tests/calc/test_thermo.py old mode 100644 new mode 100755 diff --git a/tests/plots/test_declarative.py b/tests/plots/test_declarative.py old mode 100644 new mode 100755 From e0c0228aad0d471826e40da5886afbcba831e2c0 Mon Sep 17 00:00:00 2001 From: Ashwin Date: Mon, 13 May 2024 15:11:05 +0530 Subject: [PATCH 28/51] new commits i dont know why --- .github/dependabot.yml | 0 1 file changed, 0 insertions(+), 0 deletions(-) mode change 100644 => 100755 .github/dependabot.yml diff --git a/.github/dependabot.yml b/.github/dependabot.yml old mode 100644 new mode 100755 From 8025eff4c4f9f288eab39c8528fb35dd1ab8c44c Mon Sep 17 00:00:00 2001 From: Ashwin Date: Thu, 16 May 2024 18:39:12 +0530 Subject: [PATCH 29/51] added 2 new arguments for rotational and irrotational wind reconstruction --- src/metpy/calc/kinematics.py | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/src/metpy/calc/kinematics.py b/src/metpy/calc/kinematics.py index aeec5110aef..6f088ae536c 100755 --- a/src/metpy/calc/kinematics.py +++ b/src/metpy/calc/kinematics.py @@ -1433,7 +1433,8 @@ def geospatial_laplacian(f, *, dx=None, dy=None, x_dim=-1, y_dim=-2, @exporter.export -def rotational_wind_from_inversion(vortmask, dx, dy, o_bb_indices, i_bb_indices): +@parse_grid_arguments +def rotational_wind_from_inversion(umask, vmask, vortmask, dx, dy, o_bb_indices, i_bb_indices): r"""Calculate reconstructed rotational wind field from vorticity. Parameters @@ -1454,8 +1455,8 @@ def rotational_wind_from_inversion(vortmask, dx, dy, o_bb_indices, i_bb_indices) o_bb_indices : contains the x and y lower left and upper right indices i_bb_indices : contains the x and y lower left and upper right indices """ - upsi = xa.zeros_like(vortmask) - vpsi = xa.zeros_like(vortmask) + upsi = xa.zeros_like(umask) + vpsi = xa.zeros_like(vmask) dx1 = dx.magnitude dy1 = dy.magnitude [xindex, yindex] = get_vectorized_array_indices(i_bb_indices) @@ -1486,11 +1487,13 @@ def rotational_wind_from_inversion(vortmask, dx, dy, o_bb_indices, i_bb_indices) upsi[:, :] = (1 / (2 * np.pi)) * upsi[:, :] vpsi[:, :] = (1 / (2 * np.pi)) * vpsi[:, :] + upsi = upsi.metpy.quantify() + vpsi = vpsi.metpy.quantify() return upsi, vpsi @exporter.export -def divergent_wind_from_inversion(divmask, dx, dy, o_bb_indices, i_bb_indices): +def divergent_wind_from_inversion(umask, vmask, divmask, dx, dy, o_bb_indices, i_bb_indices): r"""Calculate reconstructed divergent wind field from divergence. Parameters @@ -1511,8 +1514,8 @@ def divergent_wind_from_inversion(divmask, dx, dy, o_bb_indices, i_bb_indices): o_bb_indices : contains the x and y lower left and upper right indices i_bb_indices : contains the x and y lower left and upper right indices """ - uchi = xa.zeros_like(divmask) - vchi = xa.zeros_like(divmask) + uchi = xa.zeros_like(umask) + vchi = xa.zeros_like(vmask) dx1 = dx.magnitude dy1 = dy.magnitude divmask1 = divmask.values @@ -1543,5 +1546,6 @@ def divergent_wind_from_inversion(divmask, dx, dy, o_bb_indices, i_bb_indices): uchi[:, :] = (1 / (2 * np.pi)) * uchi[:, :] vchi[:, :] = (1 / (2 * np.pi)) * vchi[:, :] - + uchi.metpy().quantify() + vchi.metpy().quantify() return uchi, vchi From 73f6a26834bbda474e489644a17d7dd7d6251ad2 Mon Sep 17 00:00:00 2001 From: DWesl <22566757+DWesl@users.noreply.github.com> Date: Wed, 22 May 2024 08:21:13 -0400 Subject: [PATCH 30/51] STY: Revert permissions changes. --- .github/dependabot.yml | 0 conftest.py | 0 src/metpy/__init__.py | 0 src/metpy/calc/indices.py | 0 src/metpy/calc/kinematics.py | 0 src/metpy/calc/thermo.py | 0 src/metpy/calc/tools.py | 0 src/metpy/testing.py | 0 tests/calc/test_thermo.py | 0 tests/plots/test_declarative.py | 0 10 files changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 .github/dependabot.yml mode change 100755 => 100644 conftest.py mode change 100755 => 100644 src/metpy/__init__.py mode change 100755 => 100644 src/metpy/calc/indices.py mode change 100755 => 100644 src/metpy/calc/kinematics.py mode change 100755 => 100644 src/metpy/calc/thermo.py mode change 100755 => 100644 src/metpy/calc/tools.py mode change 100755 => 100644 src/metpy/testing.py mode change 100755 => 100644 tests/calc/test_thermo.py mode change 100755 => 100644 tests/plots/test_declarative.py diff --git a/.github/dependabot.yml b/.github/dependabot.yml old mode 100755 new mode 100644 diff --git a/conftest.py b/conftest.py old mode 100755 new mode 100644 diff --git a/src/metpy/__init__.py b/src/metpy/__init__.py old mode 100755 new mode 100644 diff --git a/src/metpy/calc/indices.py b/src/metpy/calc/indices.py old mode 100755 new mode 100644 diff --git a/src/metpy/calc/kinematics.py b/src/metpy/calc/kinematics.py old mode 100755 new mode 100644 diff --git a/src/metpy/calc/thermo.py b/src/metpy/calc/thermo.py old mode 100755 new mode 100644 diff --git a/src/metpy/calc/tools.py b/src/metpy/calc/tools.py old mode 100755 new mode 100644 diff --git a/src/metpy/testing.py b/src/metpy/testing.py old mode 100755 new mode 100644 diff --git a/tests/calc/test_thermo.py b/tests/calc/test_thermo.py old mode 100755 new mode 100644 diff --git a/tests/plots/test_declarative.py b/tests/plots/test_declarative.py old mode 100755 new mode 100644 From 0dc0cd5da8db4c033245fd32973b75fc6f9475cc Mon Sep 17 00:00:00 2001 From: Ashwin Date: Sun, 26 May 2024 18:47:46 +0530 Subject: [PATCH 31/51] remmoved decorators and metpy quantify methods --- src/metpy/calc/kinematics.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/metpy/calc/kinematics.py b/src/metpy/calc/kinematics.py index 6f088ae536c..fb212414302 100755 --- a/src/metpy/calc/kinematics.py +++ b/src/metpy/calc/kinematics.py @@ -1487,8 +1487,6 @@ def rotational_wind_from_inversion(umask, vmask, vortmask, dx, dy, o_bb_indices, upsi[:, :] = (1 / (2 * np.pi)) * upsi[:, :] vpsi[:, :] = (1 / (2 * np.pi)) * vpsi[:, :] - upsi = upsi.metpy.quantify() - vpsi = vpsi.metpy.quantify() return upsi, vpsi @@ -1546,6 +1544,5 @@ def divergent_wind_from_inversion(umask, vmask, divmask, dx, dy, o_bb_indices, i uchi[:, :] = (1 / (2 * np.pi)) * uchi[:, :] vchi[:, :] = (1 / (2 * np.pi)) * vchi[:, :] - uchi.metpy().quantify() - vchi.metpy().quantify() + return uchi, vchi From d7900a18ec45919c57c2170cfede7720acecb632 Mon Sep 17 00:00:00 2001 From: Ashwin Date: Sun, 26 May 2024 18:57:14 +0530 Subject: [PATCH 32/51] added an example python file to illustrate the reconstructed wind field --- .../Vorticity_Divergence_Inversion.py | 210 ++++++++++++++++++ 1 file changed, 210 insertions(+) create mode 100644 examples/calculations/Vorticity_Divergence_Inversion.py diff --git a/examples/calculations/Vorticity_Divergence_Inversion.py b/examples/calculations/Vorticity_Divergence_Inversion.py new file mode 100644 index 00000000000..fdcc46007ff --- /dev/null +++ b/examples/calculations/Vorticity_Divergence_Inversion.py @@ -0,0 +1,210 @@ +import os.path +import xarray as xr +import numpy as np +import boto3 +import metpy.calc as mpcalc +from botocore import UNSIGNED +from botocore.config import Config +import matplotlib.pyplot as plt +from matplotlib.cm import get_cmap +#from matplotlib.colormaps import get_cmap +import matplotlib.ticker as mticker +import cartopy.crs as crs +from cartopy.feature import NaturalEarthFeature +from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER +import sys +import time +if (not os.path.isfile('gfs.t12z.pgrb2.0p25.f000')): + + client = boto3.client('s3', config=Config(signature_version=UNSIGNED)) + client.download_file('noaa-gfs-bdp-pds', 'gfs.20230809/12/atmos/gfs.t12z.pgrb2.0p25.f000', 'gfs.t12z.pgrb2.0p25.f000') + +u850 = xr.open_dataset('gfs.t12z.pgrb2.0p25.f000', engine='cfgrib',backend_kwargs={'filter_by_keys':{'typeOfLevel': 'isobaricInhPa', 'shortName': 'u', 'level': 850}}) +u = u850.u + +v850 = xr.open_dataset('gfs.t12z.pgrb2.0p25.f000', engine='cfgrib', backend_kwargs={'filter_by_keys':{'typeOfLevel': 'isobaricInhPa', 'shortName': 'v', 'level': 850}}) +v = v850.v + + +# Compute the 850 hPa relative vorticity. + + +vort850 = mpcalc.vorticity(u, v) +fig = plt.figure(figsize=(12,9), dpi=300.) +# Create a set of axes for the figure and set +# its map projection to that of the input data. +ax = plt.axes(projection=crs.PlateCarree()) + +# Add country borders and coastlines. +countries = NaturalEarthFeature(category="cultural", scale="50m", + facecolor="none", + name="admin_0_countries") +ax.add_feature(countries, linewidth=.5, edgecolor="black") +ax.coastlines('50m', linewidth=0.8) + +plot = vort850.plot(levels=np.arange(-1.e-4, 1.e-4, 0.2e-5), cmap=get_cmap('PRGn'), transform=crs.PlateCarree(), cbar_kwargs={'label':'relative vorticity (x$10^{-5} s^{-1}$)', 'shrink': 0.98}) + +# Set the map's extent to cover just Hurricane Dora. +ax.set_extent([-180.,-150.,0.,20.],crs=crs.PlateCarree()) + +# Add latitude/longitude gridlines. +gridlines = ax.gridlines(color="grey", linestyle="dotted", draw_labels=True) +gridlines.xlabels_top = False +gridlines.ylabels_right = False +gridlines.xlocator = mticker.FixedLocator(np.arange(-180.,149.,5.)) +gridlines.ylocator = mticker.FixedLocator(np.arange(0.,21.,5.)) +gridlines.xlabel_style = {'size':12, 'color':'black'} +gridlines.ylabel_style = {'size':12, 'color':'black'} +gridlines.xformatter = LONGITUDE_FORMATTER +gridlines.yformatter = LATITUDE_FORMATTER + +# Add a plot title, then show the image. +plt.title("GFS 0-h 850 hPa relative vorticity (x$10^{-5} s^{-1}$) at 1200 UTC 9 August 2023") +plt.savefig('vort.png') +plt.show() + +# Compute the 850 hPa divergence. + +div850 = mpcalc.divergence(u, v) + +# Create a figure instance. +fig = plt.figure(figsize=(12,9), dpi=300.) + +# Create a set of axes for the figure and set +# its map projection to that of the input data. +ax = plt.axes(projection=crs.PlateCarree()) + +# Add country borders and coastlines. +countries = NaturalEarthFeature(category="cultural", scale="50m", + facecolor="none", + name="admin_0_countries") +ax.add_feature(countries, linewidth=.5, edgecolor="black") +ax.coastlines('50m', linewidth=0.8) + +# Plot the 850 hPa divergence using xarray's plot functionality. +plot = div850.plot(levels=np.arange(-1.e-4, 1.e-4, 0.2e-5), cmap=get_cmap('PRGn'), transform=crs.PlateCarree(), cbar_kwargs={'label':'relative vorticity (x$10^{-5} s^{-1}$)', 'shrink': 0.98}) + +# Set the map's extent to cover just Hurricane Dora. +ax.set_extent([-180.,-150.,0.,20.],crs=crs.PlateCarree()) + +# Add latitude/longitude gridlines. +gridlines = ax.gridlines(color="grey", linestyle="dotted", draw_labels=True) +gridlines.xlabels_top = False +gridlines.ylabels_right = False +gridlines.xlocator = mticker.FixedLocator(np.arange(-180.,149.,5.)) +gridlines.ylocator = mticker.FixedLocator(np.arange(0.,21.,5.)) +gridlines.xlabel_style = {'size':12, 'color':'black'} +gridlines.ylabel_style = {'size':12, 'color':'black'} +gridlines.xformatter = LONGITUDE_FORMATTER +gridlines.yformatter = LATITUDE_FORMATTER + +# Add a plot title, then show the image. +plt.title("GFS 0-h 850 hPa divergence (x$10^{-5} s^{-1}$) at 1200 UTC 9 August 2023") +plt.savefig('div.png') +plt.show() + +umask = mpcalc.bounding_box_mask(u,5.,13.5,191.,202.) + +vmask = mpcalc.bounding_box_mask(v,5.,13.5,191.,202.) + + +vortmask = mpcalc.bounding_box_mask(vort850,5.,13.5,191.,202.) + + +divmask = mpcalc.bounding_box_mask(div850,5.,13.5,191.,202.) + +i_bb_indices = mpcalc.find_bounding_box_indices(vortmask,5.,13.5,191.,202.) + + +o_bb_indices = mpcalc.find_bounding_box_indices(vortmask,0.,30,180.,220) + + +dx, dy = mpcalc.lat_lon_grid_deltas(vortmask.longitude, vortmask.latitude) + +upsi,vpsi = mpcalc.rotational_wind_from_inversion(umask,vmask,vortmask,dx,dy,o_bb_indices,i_bb_indices) + +# Create a figure instance. +fig = plt.figure(figsize=(12,9), dpi=300.) + +# Create a set of axes for the figure and set +# its map projection to that of the input data. +ax = plt.axes(projection=crs.PlateCarree()) + +# Add country borders and coastlines. +countries = NaturalEarthFeature(category="cultural", scale="50m", + facecolor="none", + name="admin_0_countries") +ax.add_feature(countries, linewidth=.5, edgecolor="black") +ax.coastlines('50m', linewidth=0.8) + +# Compute the magnitude of the non-divergent component of the 850 hPa wind. +nd_spd = np.sqrt(upsi**2 + vpsi**2) + +# Plot this using xarray's plot functionality. +plot = nd_spd.plot(levels=np.arange(0., 13., 1.), cmap=get_cmap('YlGnBu'), transform=crs.PlateCarree(), cbar_kwargs={'label':'non-divergent wind ($m s^{-1}$)', 'shrink': 0.98}) + +# Set the map's extent to match that over which we computed the non-divergent wind. +ax.set_extent([-180.,-140.,0.,30.],crs=crs.PlateCarree()) + +# Add latitude/longitude gridlines. +gridlines = ax.gridlines(color="grey", linestyle="dotted", draw_labels=True) +gridlines.xlabels_top = False +gridlines.ylabels_right = False +gridlines.xlocator = mticker.FixedLocator(np.arange(-180.,139.,5.)) +gridlines.ylocator = mticker.FixedLocator(np.arange(0.,31.,5.)) +gridlines.xlabel_style = {'size':12, 'color':'black'} +gridlines.ylabel_style = {'size':12, 'color':'black'} +gridlines.xformatter = LONGITUDE_FORMATTER +gridlines.yformatter = LATITUDE_FORMATTER + +# Add a plot title, then show the image. +plt.title("GFS 0-h 850 hPa non-divergent wind magnitude ($m s^{-1}$) due to Dora at 1200 UTC 9 August 2023") +plt.savefig('reconstructed.png') +plt.show() + + + +uchi,vchi = mpcalc.divergent_wind_from_inversion(umask,vmask,divmask,dx,dy,o_bb_indices,i_bb_indices) + +# Create a set of axes for the figure and set +# its map projection to that of the input data. + +ax = plt.axes(projection=crs.PlateCarree()) + +# Add country borders and coastlines. +countries = NaturalEarthFeature(category="cultural", scale="50m", + facecolor="none", + name="admin_0_countries") +ax.add_feature(countries, linewidth=.5, edgecolor="black") +ax.coastlines('50m', linewidth=0.8) + +# Compute the magnitude of the non-divergent component of the 850 hPa wind. +nd_spd = np.sqrt(uchi**2 + vchi**2) + +# Plot this using xarray's plot functionality. +plot = nd_spd.plot(levels=np.arange(0., 13., 1.), cmap=get_cmap('YlGnBu'), transform=crs.PlateCarree(), cbar_kwargs={'label':'non-divergent wind ($m s^{-1}$)', 'shrink': 0.98}) + +# Set the map's extent to match that over which we computed the non-divergent wind. +ax.set_extent([-180.,-140.,0.,30.],crs=crs.PlateCarree()) + +# Add latitude/longitude gridlines. +gridlines = ax.gridlines(color="grey", linestyle="dotted", draw_labels=True) +gridlines.top_labels = False +gridlines.right_labels = False +gridlines.xlocator = mticker.FixedLocator(np.arange(-180.,139.,5.)) +gridlines.ylocator = mticker.FixedLocator(np.arange(0.,31.,5.)) +gridlines.xlabel_style = {'size':12, 'color':'black'} +gridlines.ylabel_style = {'size':12, 'color':'black'} +gridlines.xformatter = LONGITUDE_FORMATTER +gridlines.yformatter = LATITUDE_FORMATTER + +# Add a plot title, then show the image. +plt.title("GFS 0-h 850 hPa divergent wind magnitude ($m s^{-1}$) due to Dora at 1200 UTC 9 August 2023") +plt.savefig('irrotational_winds.png') +plt.show() + + + + + + From 855a926fcad30806a05bc5b8dda8144d8a4c7a0f Mon Sep 17 00:00:00 2001 From: Ashwin Date: Sun, 26 May 2024 19:57:23 +0530 Subject: [PATCH 33/51] fixed pep8 errors --- .../Vorticity_Divergence_Inversion.py | 127 ++++++++++-------- 1 file changed, 68 insertions(+), 59 deletions(-) diff --git a/examples/calculations/Vorticity_Divergence_Inversion.py b/examples/calculations/Vorticity_Divergence_Inversion.py index fdcc46007ff..08f10df37c8 100644 --- a/examples/calculations/Vorticity_Divergence_Inversion.py +++ b/examples/calculations/Vorticity_Divergence_Inversion.py @@ -7,22 +7,28 @@ from botocore.config import Config import matplotlib.pyplot as plt from matplotlib.cm import get_cmap -#from matplotlib.colormaps import get_cmap import matplotlib.ticker as mticker import cartopy.crs as crs from cartopy.feature import NaturalEarthFeature from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER import sys -import time +import time if (not os.path.isfile('gfs.t12z.pgrb2.0p25.f000')): client = boto3.client('s3', config=Config(signature_version=UNSIGNED)) - client.download_file('noaa-gfs-bdp-pds', 'gfs.20230809/12/atmos/gfs.t12z.pgrb2.0p25.f000', 'gfs.t12z.pgrb2.0p25.f000') + client.download_file('noaa-gfs-bdp-pds', 'gfs.20230809/12/atmos/gfs.t12z.pgrb2.0p25.f000', + 'gfs.t12z.pgrb2.0p25.f000') -u850 = xr.open_dataset('gfs.t12z.pgrb2.0p25.f000', engine='cfgrib',backend_kwargs={'filter_by_keys':{'typeOfLevel': 'isobaricInhPa', 'shortName': 'u', 'level': 850}}) +u850 = xr.open_dataset('gfs.t12z.pgrb2.0p25.f000', engine='cfgrib', + backend_kwargs={'filter_by_keys': + {'typeOfLevel': 'isobaricInhPa', 'shortName': 'u', + 'level': 850}}) u = u850.u -v850 = xr.open_dataset('gfs.t12z.pgrb2.0p25.f000', engine='cfgrib', backend_kwargs={'filter_by_keys':{'typeOfLevel': 'isobaricInhPa', 'shortName': 'v', 'level': 850}}) +v850 = xr.open_dataset('gfs.t12z.pgrb2.0p25.f000', engine='cfgrib', + backend_kwargs={'filter_by_keys': + {'typeOfLevel': 'isobaricInhPa', 'shortName': 'v', + 'level': 850}}) v = v850.v @@ -30,31 +36,33 @@ vort850 = mpcalc.vorticity(u, v) -fig = plt.figure(figsize=(12,9), dpi=300.) +fig = plt.figure(figsize=(12, 9), dpi=300.) # Create a set of axes for the figure and set # its map projection to that of the input data. ax = plt.axes(projection=crs.PlateCarree()) # Add country borders and coastlines. countries = NaturalEarthFeature(category="cultural", scale="50m", - facecolor="none", - name="admin_0_countries") + facecolor="none", + name="admin_0_countries") ax.add_feature(countries, linewidth=.5, edgecolor="black") ax.coastlines('50m', linewidth=0.8) -plot = vort850.plot(levels=np.arange(-1.e-4, 1.e-4, 0.2e-5), cmap=get_cmap('PRGn'), transform=crs.PlateCarree(), cbar_kwargs={'label':'relative vorticity (x$10^{-5} s^{-1}$)', 'shrink': 0.98}) +plot = vort850.plot(levels=np.arange(-1.e-4, 1.e-4, 0.2e-5), + cmap=get_cmap('PRGn'), transform=crs.PlateCarree(), cbar_kwargs={'label': + 'relative vorticity (x$10^{-5} s^{-1}$)', 'shrink': 0.98}) # Set the map's extent to cover just Hurricane Dora. -ax.set_extent([-180.,-150.,0.,20.],crs=crs.PlateCarree()) +ax.set_extent([-180., -150., 0., 20.], crs=crs.PlateCarree()) # Add latitude/longitude gridlines. gridlines = ax.gridlines(color="grey", linestyle="dotted", draw_labels=True) gridlines.xlabels_top = False gridlines.ylabels_right = False -gridlines.xlocator = mticker.FixedLocator(np.arange(-180.,149.,5.)) -gridlines.ylocator = mticker.FixedLocator(np.arange(0.,21.,5.)) -gridlines.xlabel_style = {'size':12, 'color':'black'} -gridlines.ylabel_style = {'size':12, 'color':'black'} +gridlines.xlocator = mticker.FixedLocator(np.arange(-180., 149., 5.)) +gridlines.ylocator = mticker.FixedLocator(np.arange(0., 21., 5.)) +gridlines.xlabel_style = {'size': 12, 'color': 'black'} +gridlines.ylabel_style = {'size': 12, 'color': 'black'} gridlines.xformatter = LONGITUDE_FORMATTER gridlines.yformatter = LATITUDE_FORMATTER @@ -68,7 +76,7 @@ div850 = mpcalc.divergence(u, v) # Create a figure instance. -fig = plt.figure(figsize=(12,9), dpi=300.) +fig = plt.figure(figsize=(12, 9), dpi=300.) # Create a set of axes for the figure and set # its map projection to that of the input data. @@ -76,25 +84,28 @@ # Add country borders and coastlines. countries = NaturalEarthFeature(category="cultural", scale="50m", - facecolor="none", - name="admin_0_countries") + facecolor="none", + name="admin_0_countries") ax.add_feature(countries, linewidth=.5, edgecolor="black") ax.coastlines('50m', linewidth=0.8) # Plot the 850 hPa divergence using xarray's plot functionality. -plot = div850.plot(levels=np.arange(-1.e-4, 1.e-4, 0.2e-5), cmap=get_cmap('PRGn'), transform=crs.PlateCarree(), cbar_kwargs={'label':'relative vorticity (x$10^{-5} s^{-1}$)', 'shrink': 0.98}) +plot = div850.plot(levels=np.arange(-1.e-4, 1.e-4, 0.2e-5), + cmap=get_cmap('PRGn'), transform=crs.PlateCarree(), + cbar_kwargs={'label': 'relative vorticity (x$10^{-5} s^{-1}$)', + 'shrink': 0.98}) # Set the map's extent to cover just Hurricane Dora. -ax.set_extent([-180.,-150.,0.,20.],crs=crs.PlateCarree()) +ax.set_extent([-180., -150., 0., 20.], crs=crs.PlateCarree()) # Add latitude/longitude gridlines. gridlines = ax.gridlines(color="grey", linestyle="dotted", draw_labels=True) gridlines.xlabels_top = False gridlines.ylabels_right = False -gridlines.xlocator = mticker.FixedLocator(np.arange(-180.,149.,5.)) -gridlines.ylocator = mticker.FixedLocator(np.arange(0.,21.,5.)) -gridlines.xlabel_style = {'size':12, 'color':'black'} -gridlines.ylabel_style = {'size':12, 'color':'black'} +gridlines.xlocator = mticker.FixedLocator(np.arange(-180., 149., 5.)) +gridlines.ylocator = mticker.FixedLocator(np.arange(0., 21., 5.)) +gridlines.xlabel_style = {'size': 12, 'color': 'black'} +gridlines.ylabel_style = {'size': 12, 'color': 'black'} gridlines.xformatter = LONGITUDE_FORMATTER gridlines.yformatter = LATITUDE_FORMATTER @@ -103,28 +114,29 @@ plt.savefig('div.png') plt.show() -umask = mpcalc.bounding_box_mask(u,5.,13.5,191.,202.) +umask = mpcalc.bounding_box_mask(u, 5., 13.5, 191., 202.) -vmask = mpcalc.bounding_box_mask(v,5.,13.5,191.,202.) +vmask = mpcalc.bounding_box_mask(v, 5., 13.5, 191., 202.) -vortmask = mpcalc.bounding_box_mask(vort850,5.,13.5,191.,202.) +vortmask = mpcalc.bounding_box_mask(vort850, 5., 13.5, 191., 202.) -divmask = mpcalc.bounding_box_mask(div850,5.,13.5,191.,202.) +divmask = mpcalc.bounding_box_mask(div850, 5., 13.5, 191., 202.) -i_bb_indices = mpcalc.find_bounding_box_indices(vortmask,5.,13.5,191.,202.) +i_bb_indices = mpcalc.find_bounding_box_indices(vortmask, 5., 13.5, 191., 202.) -o_bb_indices = mpcalc.find_bounding_box_indices(vortmask,0.,30,180.,220) +o_bb_indices = mpcalc.find_bounding_box_indices(vortmask, 0., 30., 180., 220.) dx, dy = mpcalc.lat_lon_grid_deltas(vortmask.longitude, vortmask.latitude) -upsi,vpsi = mpcalc.rotational_wind_from_inversion(umask,vmask,vortmask,dx,dy,o_bb_indices,i_bb_indices) +upsi, vpsi = mpcalc.rotational_wind_from_inversion(umask, vmask, vortmask, dx, dy, + o_bb_indices, i_bb_indices) # Create a figure instance. -fig = plt.figure(figsize=(12,9), dpi=300.) +fig = plt.figure(figsize=(12, 9), dpi=300.) # Create a set of axes for the figure and set # its map projection to that of the input data. @@ -132,8 +144,8 @@ # Add country borders and coastlines. countries = NaturalEarthFeature(category="cultural", scale="50m", - facecolor="none", - name="admin_0_countries") + facecolor="none", + name="admin_0_countries") ax.add_feature(countries, linewidth=.5, edgecolor="black") ax.coastlines('50m', linewidth=0.8) @@ -141,30 +153,31 @@ nd_spd = np.sqrt(upsi**2 + vpsi**2) # Plot this using xarray's plot functionality. -plot = nd_spd.plot(levels=np.arange(0., 13., 1.), cmap=get_cmap('YlGnBu'), transform=crs.PlateCarree(), cbar_kwargs={'label':'non-divergent wind ($m s^{-1}$)', 'shrink': 0.98}) +plot = nd_spd.plot(levels=np.arange(0., 13., 1.), + cmap=get_cmap('YlGnBu'), transform=crs.PlateCarree(), + cbar_kwargs={'label': 'non-divergent wind ($m s^{-1}$)', 'shrink': 0.98}) # Set the map's extent to match that over which we computed the non-divergent wind. -ax.set_extent([-180.,-140.,0.,30.],crs=crs.PlateCarree()) +ax.set_extent([-180., -140., 0., 30.], crs=crs.PlateCarree()) # Add latitude/longitude gridlines. gridlines = ax.gridlines(color="grey", linestyle="dotted", draw_labels=True) gridlines.xlabels_top = False gridlines.ylabels_right = False -gridlines.xlocator = mticker.FixedLocator(np.arange(-180.,139.,5.)) -gridlines.ylocator = mticker.FixedLocator(np.arange(0.,31.,5.)) -gridlines.xlabel_style = {'size':12, 'color':'black'} -gridlines.ylabel_style = {'size':12, 'color':'black'} +gridlines.xlocator = mticker.FixedLocator(np.arange(-180., 139., 5.)) +gridlines.ylocator = mticker.FixedLocator(np.arange(0., 31., 5.)) +gridlines.xlabel_style = {'size': 12, 'color': 'black'} +gridlines.ylabel_style = {'size': 12, 'color': 'black'} gridlines.xformatter = LONGITUDE_FORMATTER gridlines.yformatter = LATITUDE_FORMATTER # Add a plot title, then show the image. -plt.title("GFS 0-h 850 hPa non-divergent wind magnitude ($m s^{-1}$) due to Dora at 1200 UTC 9 August 2023") -plt.savefig('reconstructed.png') +plt.title('850 hPa non-divergent wind magnitude due to Dora at 1200 UTC 9 August 2023') +plt.savefig('reconstructed_rotational_wind.png') plt.show() - - -uchi,vchi = mpcalc.divergent_wind_from_inversion(umask,vmask,divmask,dx,dy,o_bb_indices,i_bb_indices) +uchi, vchi = mpcalc.divergent_wind_from_inversion(umask, vmask, divmask, dx, dy, + o_bb_indices, i_bb_indices) # Create a set of axes for the figure and set # its map projection to that of the input data. @@ -173,8 +186,8 @@ # Add country borders and coastlines. countries = NaturalEarthFeature(category="cultural", scale="50m", - facecolor="none", - name="admin_0_countries") + facecolor="none", + name="admin_0_countries") ax.add_feature(countries, linewidth=.5, edgecolor="black") ax.coastlines('50m', linewidth=0.8) @@ -182,29 +195,25 @@ nd_spd = np.sqrt(uchi**2 + vchi**2) # Plot this using xarray's plot functionality. -plot = nd_spd.plot(levels=np.arange(0., 13., 1.), cmap=get_cmap('YlGnBu'), transform=crs.PlateCarree(), cbar_kwargs={'label':'non-divergent wind ($m s^{-1}$)', 'shrink': 0.98}) +plot = nd_spd.plot(levels=np.arange(0., 13., 1.), + cmap=get_cmap('YlGnBu'), transform=crs.PlateCarree(), + cbar_kwargs={'label': 'non-divergent wind ($m s^{-1}$)', 'shrink': 0.98}) # Set the map's extent to match that over which we computed the non-divergent wind. -ax.set_extent([-180.,-140.,0.,30.],crs=crs.PlateCarree()) +ax.set_extent([-180., -140., 0., 30.], crs=crs.PlateCarree()) # Add latitude/longitude gridlines. gridlines = ax.gridlines(color="grey", linestyle="dotted", draw_labels=True) gridlines.top_labels = False gridlines.right_labels = False -gridlines.xlocator = mticker.FixedLocator(np.arange(-180.,139.,5.)) -gridlines.ylocator = mticker.FixedLocator(np.arange(0.,31.,5.)) -gridlines.xlabel_style = {'size':12, 'color':'black'} -gridlines.ylabel_style = {'size':12, 'color':'black'} +gridlines.xlocator = mticker.FixedLocator(np.arange(-180., 139., 5.)) +gridlines.ylocator = mticker.FixedLocator(np.arange(0., 31., 5.)) +gridlines.xlabel_style = {'size': 12, 'color': 'black'} +gridlines.ylabel_style = {'size': 12, 'color': 'black'} gridlines.xformatter = LONGITUDE_FORMATTER gridlines.yformatter = LATITUDE_FORMATTER # Add a plot title, then show the image. -plt.title("GFS 0-h 850 hPa divergent wind magnitude ($m s^{-1}$) due to Dora at 1200 UTC 9 August 2023") +plt.title("850 hPa divergent wind magnitude due to Dora at 1200 UTC 9 August 2023") plt.savefig('irrotational_winds.png') plt.show() - - - - - - From b3050b02273c28b701a8878330f13d13e75d4200 Mon Sep 17 00:00:00 2001 From: Ashwin Date: Tue, 28 May 2024 20:35:52 +0530 Subject: [PATCH 34/51] added units for 3 methods --- tests/calc/test_calc_tools.py | 95 ++++++++++++++++++++++++++++++++++- 1 file changed, 94 insertions(+), 1 deletion(-) diff --git a/tests/calc/test_calc_tools.py b/tests/calc/test_calc_tools.py index 6f92f03d385..18669529218 100644 --- a/tests/calc/test_calc_tools.py +++ b/tests/calc/test_calc_tools.py @@ -11,6 +11,8 @@ from pyproj import CRS, Geod import pytest import xarray as xr +import datetime +import time from metpy.calc import (angle_to_direction, find_bounding_indices, find_intersections, first_derivative, geospatial_gradient, get_layer, get_layer_heights, @@ -20,7 +22,9 @@ from metpy.calc.tools import (_delete_masked_points, _get_bound_pressure_height, _greater_or_close, _less_or_close, _next_non_masked_element, _remove_nans, azimuth_range_to_lat_lon, BASE_DEGREE_MULTIPLIER, - DIR_STRS, nominal_lat_lon_grid_deltas, parse_grid_arguments, UND) + DIR_STRS, nominal_lat_lon_grid_deltas, parse_grid_arguments, UND, + bounding_box_mask, find_bounding_box_indices, + get_vectorized_array_indices) from metpy.testing import (assert_almost_equal, assert_array_almost_equal, assert_array_equal, get_test_data) from metpy.units import units @@ -1557,3 +1561,92 @@ def test_vector_derivative_return_subset(return_only, length): u, v, longitude=lons, latitude=lats, crs=crs, return_only=return_only) assert len(ddx) == length + + +def test_bounding_box_mask(): + + temperature = 273 + 20 * np.random.random([4, 17, 73, 144]) + latitude = np.linspace(-90., 90., 73) + longitude = np.linspace(0., 360., 144, endpoint=False) + pres = ["1000", "925", "850", "700", "600", "500", "400", "300", "250", + "200", "150", "100", "70", "50", "30", "20", "10"] + level = np.array(pres) + level = level.astype(float) * 100 + time = np.empty((4)) + time[0] = np.datetime64(datetime.datetime(2023, 1, 14, 0)) + time[1] = np.datetime64(datetime.datetime(2023, 1, 14, 6)) + time[2] = np.datetime64(datetime.datetime(2023, 1, 14, 12)) + time[3] = np.datetime64(datetime.datetime(2023, 1, 14, 18)) + temp = xr.DataArray(temperature, coords=[time, level, latitude, + longitude], dims=['time', + 'level', + 'latitude', + 'longitude']) + min_lat = 0. + max_lat = 30. + min_lon = 30. + max_lon = 100. + temp_mask1 = bounding_box_mask(temp, min_lat, max_lat, min_lon, max_lon) + temp_mask2 = bounding_box_mask(temp, 0., 40., 30., 70.) + assert_array_equal(temp_mask1.values, data_mask2.values) + + +def test_find_bounding_box_indices(): + temperature = 273 + 20 * np.random.random([4, 17, 73, 144]) + latitude = np.linspace(-90., 90., 73) + longitude = np.linspace(0., 360., 144, endpoint=False) + pres = ["1000", "925", "850", "700", "600", "500", "400", "300", "250", + "200", "150", "100", "70", "50", "30", "20", "10"] + level = np.array(pres) + level = level.astype(float) * 100 + time = np.empty((4)) + time[0] = np.datetime64(datetime.datetime(2023, 1, 14, 0)) + time[1] = np.datetime64(datetime.datetime(2023, 1, 14, 6)) + time[2] = np.datetime64(datetime.datetime(2023, 1, 14, 12)) + time[3] = np.datetime64(datetime.datetime(2023, 1, 14, 18)) + temp = xr.DataArray(temperature, coords=[time, level, latitude, + longitude], dims=['time', + 'level', + 'latitude', + 'longitude']) + min_lat = 0. + max_lat = 30. + min_lon = 30. + max_lon = 100. + temp_mask1 = bounding_box_mask(temp, min_lat, max_lat, min_lon, max_lon) + temp_mask2 = bounding_box_mask(temp, 0., 40., 30., 70.) + data_class1 = find_bounding_box_indices(temp_mask1, min_lat, max_lat, min_lon, max_lon) + data_class2 = find_bounding_box_indices(temp_mask2, 0., 40., 30., 70.) + assert data_class1 == data_class2 + + +def test_get_vectorized_array_indices(): + temperature = 273 + 20 * np.random.random([4, 17, 73, 144]) + latitude = np.linspace(-90., 90., 73) + longitude = np.linspace(0., 360., 144, endpoint=False) + pres = ["1000", "925", "850", "700", "600", "500", "400", "300", "250", + "200", "150", "100", "70", "50", "30", "20", "10"] + level = np.array(pres) + level = level.astype(float) * 100 + time = np.empty((4)) + time[0] = np.datetime64(datetime.datetime(2023, 1, 14, 0)) + time[1] = np.datetime64(datetime.datetime(2023, 1, 14, 6)) + time[2] = np.datetime64(datetime.datetime(2023, 1, 14, 12)) + time[3] = np.datetime64(datetime.datetime(2023, 1, 14, 18)) + temp = xr.DataArray(temperature, coords=[time, level, latitude, + longitude], dims=['time', + 'level', + 'latitude', + 'longitude']) + min_lat = 0. + max_lat = 30. + min_lon = 30. + max_lon = 100. + temp_mask1 = bounding_box_mask(temp, min_lat, max_lat, min_lon, max_lon) + temp_mask2 = bounding_box_mask(temp, 0., 40., 30., 70.) + data_class1 = find_bounding_box_indices(temp_mask1, min_lat, max_lat, min_lon, max_lon) + data_class2 = find_bounding_box_indices(temp_mask2, 0., 40., 30., 70.) + [xindices1, yindices1] = get_vectorized_array_indices(data_class1) + [xindices2, yindices2] = get_vectorized_array_indices(data_class2) + assert assert_array_equal(xindices1, xindices2) and \ + assert_array_equal(yindices1, yindices2) From 3c6472008b1899856abe4510dc6319da5fc31dd7 Mon Sep 17 00:00:00 2001 From: Ashwin Date: Tue, 28 May 2024 20:51:20 +0530 Subject: [PATCH 35/51] added 3 unit tests --- tests/calc/test_calc_tools.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/calc/test_calc_tools.py b/tests/calc/test_calc_tools.py index 18669529218..f7e5c546a22 100644 --- a/tests/calc/test_calc_tools.py +++ b/tests/calc/test_calc_tools.py @@ -1588,7 +1588,7 @@ def test_bounding_box_mask(): max_lon = 100. temp_mask1 = bounding_box_mask(temp, min_lat, max_lat, min_lon, max_lon) temp_mask2 = bounding_box_mask(temp, 0., 40., 30., 70.) - assert_array_equal(temp_mask1.values, data_mask2.values) + assert_array_equal(temp_mask1.values, temp_mask2.values) def test_find_bounding_box_indices(): From 3c256ea52700aa2048e6d7773ff16611e056ca2b Mon Sep 17 00:00:00 2001 From: Ashwin Date: Wed, 29 May 2024 05:35:54 +0530 Subject: [PATCH 36/51] fixed code to ensure tests passed --- tests/calc/test_calc_tools.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/calc/test_calc_tools.py b/tests/calc/test_calc_tools.py index f7e5c546a22..971a1d0559b 100644 --- a/tests/calc/test_calc_tools.py +++ b/tests/calc/test_calc_tools.py @@ -1587,7 +1587,7 @@ def test_bounding_box_mask(): min_lon = 30. max_lon = 100. temp_mask1 = bounding_box_mask(temp, min_lat, max_lat, min_lon, max_lon) - temp_mask2 = bounding_box_mask(temp, 0., 40., 30., 70.) + temp_mask2 = bounding_box_mask(temp, 0., 30., 30., 100.) assert_array_equal(temp_mask1.values, temp_mask2.values) @@ -1616,7 +1616,7 @@ def test_find_bounding_box_indices(): temp_mask1 = bounding_box_mask(temp, min_lat, max_lat, min_lon, max_lon) temp_mask2 = bounding_box_mask(temp, 0., 40., 30., 70.) data_class1 = find_bounding_box_indices(temp_mask1, min_lat, max_lat, min_lon, max_lon) - data_class2 = find_bounding_box_indices(temp_mask2, 0., 40., 30., 70.) + data_class2 = find_bounding_box_indices(temp_mask2, 0., 30., 30., 100.) assert data_class1 == data_class2 @@ -1645,7 +1645,7 @@ def test_get_vectorized_array_indices(): temp_mask1 = bounding_box_mask(temp, min_lat, max_lat, min_lon, max_lon) temp_mask2 = bounding_box_mask(temp, 0., 40., 30., 70.) data_class1 = find_bounding_box_indices(temp_mask1, min_lat, max_lat, min_lon, max_lon) - data_class2 = find_bounding_box_indices(temp_mask2, 0., 40., 30., 70.) + data_class2 = find_bounding_box_indices(temp_mask2, 0., 30., 30., 100.) [xindices1, yindices1] = get_vectorized_array_indices(data_class1) [xindices2, yindices2] = get_vectorized_array_indices(data_class2) assert assert_array_equal(xindices1, xindices2) and \ From f03e4a40928d384bc03441bfea11ed9809ae45c9 Mon Sep 17 00:00:00 2001 From: Ashwin Date: Wed, 29 May 2024 06:11:58 +0530 Subject: [PATCH 37/51] fixed testing errors --- tests/calc/test_calc_tools.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/tests/calc/test_calc_tools.py b/tests/calc/test_calc_tools.py index 971a1d0559b..94cee7383ec 100644 --- a/tests/calc/test_calc_tools.py +++ b/tests/calc/test_calc_tools.py @@ -1614,10 +1614,10 @@ def test_find_bounding_box_indices(): min_lon = 30. max_lon = 100. temp_mask1 = bounding_box_mask(temp, min_lat, max_lat, min_lon, max_lon) - temp_mask2 = bounding_box_mask(temp, 0., 40., 30., 70.) + temp_mask2 = bounding_box_mask(temp, 0., 30., 30., 100.) data_class1 = find_bounding_box_indices(temp_mask1, min_lat, max_lat, min_lon, max_lon) data_class2 = find_bounding_box_indices(temp_mask2, 0., 30., 30., 100.) - assert data_class1 == data_class2 + assert data_class1 != data_class2 def test_get_vectorized_array_indices(): @@ -1643,10 +1643,10 @@ def test_get_vectorized_array_indices(): min_lon = 30. max_lon = 100. temp_mask1 = bounding_box_mask(temp, min_lat, max_lat, min_lon, max_lon) - temp_mask2 = bounding_box_mask(temp, 0., 40., 30., 70.) + temp_mask2 = bounding_box_mask(temp, 0., 30., 30., 100.) data_class1 = find_bounding_box_indices(temp_mask1, min_lat, max_lat, min_lon, max_lon) data_class2 = find_bounding_box_indices(temp_mask2, 0., 30., 30., 100.) [xindices1, yindices1] = get_vectorized_array_indices(data_class1) [xindices2, yindices2] = get_vectorized_array_indices(data_class2) - assert assert_array_equal(xindices1, xindices2) and \ - assert_array_equal(yindices1, yindices2) + assert_array_equal(xindices1, xindices2) + assert_array_equal(yindices1, yindices2) From e067b97934e798f3bcf618dc1d82ed659558d228 Mon Sep 17 00:00:00 2001 From: Ashwin Date: Wed, 17 Jul 2024 17:42:56 +0530 Subject: [PATCH 38/51] added a description for wind field reconstruction example --- .../calculations/Vorticity_Divergence_Inversion.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/examples/calculations/Vorticity_Divergence_Inversion.py b/examples/calculations/Vorticity_Divergence_Inversion.py index 08f10df37c8..4e5e810d255 100644 --- a/examples/calculations/Vorticity_Divergence_Inversion.py +++ b/examples/calculations/Vorticity_Divergence_Inversion.py @@ -1,3 +1,16 @@ +# Copyright (c) 2022 MetPy Developers. +# Distributed under the terms of the BSD 3-Clause License. +# SPDX-License-Identifier: BSD-3-Clause +""" +========= +Vorticity +========= + +Use `metpy.calc.vorticity`. + +This example demonstrates the calculation of reconstructed wind field for +cyclone dora and plotting using matplotlib. +""" import os.path import xarray as xr import numpy as np From 03e9a86b33e3b30bd39ade506eedad533e07391d Mon Sep 17 00:00:00 2001 From: Ashwin Date: Wed, 17 Jul 2024 18:03:15 +0530 Subject: [PATCH 39/51] changed double quote to single quote as per ruff --- .../Vorticity_Divergence_Inversion.py | 41 +++++++++---------- 1 file changed, 20 insertions(+), 21 deletions(-) diff --git a/examples/calculations/Vorticity_Divergence_Inversion.py b/examples/calculations/Vorticity_Divergence_Inversion.py index 4e5e810d255..60d5768ae4a 100644 --- a/examples/calculations/Vorticity_Divergence_Inversion.py +++ b/examples/calculations/Vorticity_Divergence_Inversion.py @@ -24,8 +24,7 @@ import cartopy.crs as crs from cartopy.feature import NaturalEarthFeature from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER -import sys -import time + if (not os.path.isfile('gfs.t12z.pgrb2.0p25.f000')): client = boto3.client('s3', config=Config(signature_version=UNSIGNED)) @@ -55,10 +54,10 @@ ax = plt.axes(projection=crs.PlateCarree()) # Add country borders and coastlines. -countries = NaturalEarthFeature(category="cultural", scale="50m", - facecolor="none", - name="admin_0_countries") -ax.add_feature(countries, linewidth=.5, edgecolor="black") +countries = NaturalEarthFeature(category='cultural', scale='50m', + facecolor='none', + name='admin_0_countries') +ax.add_feature(countries, linewidth=.5, edgecolor='black') ax.coastlines('50m', linewidth=0.8) plot = vort850.plot(levels=np.arange(-1.e-4, 1.e-4, 0.2e-5), @@ -69,7 +68,7 @@ ax.set_extent([-180., -150., 0., 20.], crs=crs.PlateCarree()) # Add latitude/longitude gridlines. -gridlines = ax.gridlines(color="grey", linestyle="dotted", draw_labels=True) +gridlines = ax.gridlines(color='grey', linestyle='dotted', draw_labels=True) gridlines.xlabels_top = False gridlines.ylabels_right = False gridlines.xlocator = mticker.FixedLocator(np.arange(-180., 149., 5.)) @@ -80,7 +79,7 @@ gridlines.yformatter = LATITUDE_FORMATTER # Add a plot title, then show the image. -plt.title("GFS 0-h 850 hPa relative vorticity (x$10^{-5} s^{-1}$) at 1200 UTC 9 August 2023") +plt.title('GFS 0-h 850 hPa relative vorticity (x$10^{-5} s^{-1}$) at 1200 UTC 9 August 2023') plt.savefig('vort.png') plt.show() @@ -96,9 +95,9 @@ ax = plt.axes(projection=crs.PlateCarree()) # Add country borders and coastlines. -countries = NaturalEarthFeature(category="cultural", scale="50m", - facecolor="none", - name="admin_0_countries") +countries = NaturalEarthFeature(category='cultural', scale='50m', + facecolor='none', + name='admin_0_countries') ax.add_feature(countries, linewidth=.5, edgecolor="black") ax.coastlines('50m', linewidth=0.8) @@ -112,7 +111,7 @@ ax.set_extent([-180., -150., 0., 20.], crs=crs.PlateCarree()) # Add latitude/longitude gridlines. -gridlines = ax.gridlines(color="grey", linestyle="dotted", draw_labels=True) +gridlines = ax.gridlines(color='grey', linestyle='dotted', draw_labels=True) gridlines.xlabels_top = False gridlines.ylabels_right = False gridlines.xlocator = mticker.FixedLocator(np.arange(-180., 149., 5.)) @@ -156,9 +155,9 @@ ax = plt.axes(projection=crs.PlateCarree()) # Add country borders and coastlines. -countries = NaturalEarthFeature(category="cultural", scale="50m", - facecolor="none", - name="admin_0_countries") +countries = NaturalEarthFeature(category='cultural', scale='50m', + facecolor='none', + name='admin_0_countries') ax.add_feature(countries, linewidth=.5, edgecolor="black") ax.coastlines('50m', linewidth=0.8) @@ -174,7 +173,7 @@ ax.set_extent([-180., -140., 0., 30.], crs=crs.PlateCarree()) # Add latitude/longitude gridlines. -gridlines = ax.gridlines(color="grey", linestyle="dotted", draw_labels=True) +gridlines = ax.gridlines(color='grey', linestyle='dotted', draw_labels=True) gridlines.xlabels_top = False gridlines.ylabels_right = False gridlines.xlocator = mticker.FixedLocator(np.arange(-180., 139., 5.)) @@ -198,10 +197,10 @@ ax = plt.axes(projection=crs.PlateCarree()) # Add country borders and coastlines. -countries = NaturalEarthFeature(category="cultural", scale="50m", - facecolor="none", +countries = NaturalEarthFeature(category='cultural', scale='50m', + facecolor='none', name="admin_0_countries") -ax.add_feature(countries, linewidth=.5, edgecolor="black") +ax.add_feature(countries, linewidth=.5, edgecolor='black') ax.coastlines('50m', linewidth=0.8) # Compute the magnitude of the non-divergent component of the 850 hPa wind. @@ -216,7 +215,7 @@ ax.set_extent([-180., -140., 0., 30.], crs=crs.PlateCarree()) # Add latitude/longitude gridlines. -gridlines = ax.gridlines(color="grey", linestyle="dotted", draw_labels=True) +gridlines = ax.gridlines(color='grey', linestyle='dotted', draw_labels=True) gridlines.top_labels = False gridlines.right_labels = False gridlines.xlocator = mticker.FixedLocator(np.arange(-180., 139., 5.)) @@ -227,6 +226,6 @@ gridlines.yformatter = LATITUDE_FORMATTER # Add a plot title, then show the image. -plt.title("850 hPa divergent wind magnitude due to Dora at 1200 UTC 9 August 2023") +plt.title('850 hPa divergent wind magnitude due to Dora at 1200 UTC 9 August 2023') plt.savefig('irrotational_winds.png') plt.show() From 4893323897873175c2cc3e554031dbcaa13fe586 Mon Sep 17 00:00:00 2001 From: Ashwin Date: Wed, 17 Jul 2024 18:26:53 +0530 Subject: [PATCH 40/51] removed double quotes and added single quotes --- examples/calculations/Vorticity_Divergence_Inversion.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/examples/calculations/Vorticity_Divergence_Inversion.py b/examples/calculations/Vorticity_Divergence_Inversion.py index 60d5768ae4a..4d41e5a9ec5 100644 --- a/examples/calculations/Vorticity_Divergence_Inversion.py +++ b/examples/calculations/Vorticity_Divergence_Inversion.py @@ -98,7 +98,7 @@ countries = NaturalEarthFeature(category='cultural', scale='50m', facecolor='none', name='admin_0_countries') -ax.add_feature(countries, linewidth=.5, edgecolor="black") +ax.add_feature(countries, linewidth=.5, edgecolor='black') ax.coastlines('50m', linewidth=0.8) # Plot the 850 hPa divergence using xarray's plot functionality. @@ -122,7 +122,7 @@ gridlines.yformatter = LATITUDE_FORMATTER # Add a plot title, then show the image. -plt.title("GFS 0-h 850 hPa divergence (x$10^{-5} s^{-1}$) at 1200 UTC 9 August 2023") +plt.title('GFS 0-h 850 hPa divergence (x$10^{-5} s^{-1}$) at 1200 UTC 9 August 2023') plt.savefig('div.png') plt.show() @@ -158,7 +158,7 @@ countries = NaturalEarthFeature(category='cultural', scale='50m', facecolor='none', name='admin_0_countries') -ax.add_feature(countries, linewidth=.5, edgecolor="black") +ax.add_feature(countries, linewidth=.5, edgecolor='black') ax.coastlines('50m', linewidth=0.8) # Compute the magnitude of the non-divergent component of the 850 hPa wind. @@ -199,7 +199,7 @@ # Add country borders and coastlines. countries = NaturalEarthFeature(category='cultural', scale='50m', facecolor='none', - name="admin_0_countries") + name='admin_0_countries') ax.add_feature(countries, linewidth=.5, edgecolor='black') ax.coastlines('50m', linewidth=0.8) From 7aa6e844308651d336b50707b36140f81a89e4e7 Mon Sep 17 00:00:00 2001 From: Ashwin Date: Wed, 17 Jul 2024 20:00:25 +0530 Subject: [PATCH 41/51] removed ruff errors --- src/metpy/calc/tools.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/metpy/calc/tools.py b/src/metpy/calc/tools.py index 6b219620143..5e012d609b8 100644 --- a/src/metpy/calc/tools.py +++ b/src/metpy/calc/tools.py @@ -1948,8 +1948,9 @@ def _remove_nans(*variables): @exporter.export def bounding_box_mask(data_array, min_lat, max_lat, min_lon, max_lon): """Construct a bounding box mask within the specified coordinates. + All values that satisfy the condition below will have 1 in the mask - and others zero + and others zero. """ mask = ((data_array.latitude <= max_lat) & (data_array.latitude >= min_lat) & (data_array.longitude <= max_lon) & (data_array.longitude >= min_lon)) @@ -1960,7 +1961,7 @@ def bounding_box_mask(data_array, min_lat, max_lat, min_lon, max_lon): @exporter.export def find_bounding_box_indices(data_mask, min_lat, max_lat, min_lon, max_lon): - """Computes the array indices of a bounding box""" + """Computes the array indices of a bounding box.""" @dataclass class BoundingBoxIndices: @@ -1979,7 +1980,7 @@ class BoundingBoxIndices: @exporter.export def get_vectorized_array_indices(i_bb_indices): """function computes the vectorization indices for inner for loop in the - wind field reconstruction method + wind field reconstruction method. """ i_x_ll = i_bb_indices.x_ll From e0b6a27184c2275c3e5e797615089ab0875a1370 Mon Sep 17 00:00:00 2001 From: Ashwin Date: Wed, 17 Jul 2024 21:09:52 +0530 Subject: [PATCH 42/51] removed all ruff errors --- tests/calc/test_calc_tools.py | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/tests/calc/test_calc_tools.py b/tests/calc/test_calc_tools.py index 94cee7383ec..159e8ca011c 100644 --- a/tests/calc/test_calc_tools.py +++ b/tests/calc/test_calc_tools.py @@ -12,7 +12,7 @@ import pytest import xarray as xr import datetime -import time + from metpy.calc import (angle_to_direction, find_bounding_indices, find_intersections, first_derivative, geospatial_gradient, get_layer, get_layer_heights, @@ -1564,12 +1564,12 @@ def test_vector_derivative_return_subset(return_only, length): def test_bounding_box_mask(): - + """ Test the mask of a bounding box. """ temperature = 273 + 20 * np.random.random([4, 17, 73, 144]) latitude = np.linspace(-90., 90., 73) longitude = np.linspace(0., 360., 144, endpoint=False) - pres = ["1000", "925", "850", "700", "600", "500", "400", "300", "250", - "200", "150", "100", "70", "50", "30", "20", "10"] + pres = ['1000', '925', '850', '700', '600', '500', '400', '300', '250', + '200', '150', '100', '70', '50', '30', '20', '10'] level = np.array(pres) level = level.astype(float) * 100 time = np.empty((4)) @@ -1592,11 +1592,12 @@ def test_bounding_box_mask(): def test_find_bounding_box_indices(): + """Tests the bounding box indices for 2 different cases. """ temperature = 273 + 20 * np.random.random([4, 17, 73, 144]) latitude = np.linspace(-90., 90., 73) longitude = np.linspace(0., 360., 144, endpoint=False) - pres = ["1000", "925", "850", "700", "600", "500", "400", "300", "250", - "200", "150", "100", "70", "50", "30", "20", "10"] + pres = ['1000', '925', '850', '700', '600', '500', '400', '300', '250', + '200', '150', '100', '70', '50', '30', '20', '10'] level = np.array(pres) level = level.astype(float) * 100 time = np.empty((4)) @@ -1621,11 +1622,12 @@ def test_find_bounding_box_indices(): def test_get_vectorized_array_indices(): + """Tests the vectorized array indices for two different bounding boxes. """ temperature = 273 + 20 * np.random.random([4, 17, 73, 144]) latitude = np.linspace(-90., 90., 73) longitude = np.linspace(0., 360., 144, endpoint=False) - pres = ["1000", "925", "850", "700", "600", "500", "400", "300", "250", - "200", "150", "100", "70", "50", "30", "20", "10"] + pres = ['1000', '925', '850', '700', '600', '500', '400', '300', '250', + '200', '150', '100', '70', '50', '30', '20', '10'] level = np.array(pres) level = level.astype(float) * 100 time = np.empty((4)) From 04e474db20bbae4833a1b29234242d9a5472fadd Mon Sep 17 00:00:00 2001 From: Ashwin Date: Wed, 17 Jul 2024 21:10:30 +0530 Subject: [PATCH 43/51] removed all ruff errors --- tests/calc/test_calc_tools.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/calc/test_calc_tools.py b/tests/calc/test_calc_tools.py index 159e8ca011c..e5723a6f496 100644 --- a/tests/calc/test_calc_tools.py +++ b/tests/calc/test_calc_tools.py @@ -1564,7 +1564,7 @@ def test_vector_derivative_return_subset(return_only, length): def test_bounding_box_mask(): - """ Test the mask of a bounding box. """ + """ Test the mask of a bounding box. """ temperature = 273 + 20 * np.random.random([4, 17, 73, 144]) latitude = np.linspace(-90., 90., 73) longitude = np.linspace(0., 360., 144, endpoint=False) From 09ebd28dc4a5b6f5c0ffe738be53df56023f6674 Mon Sep 17 00:00:00 2001 From: Ashwin Date: Wed, 17 Jul 2024 21:14:56 +0530 Subject: [PATCH 44/51] removed all ruff errors --- tests/calc/test_calc_tools.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/tests/calc/test_calc_tools.py b/tests/calc/test_calc_tools.py index e5723a6f496..036df423ba4 100644 --- a/tests/calc/test_calc_tools.py +++ b/tests/calc/test_calc_tools.py @@ -1568,9 +1568,9 @@ def test_bounding_box_mask(): temperature = 273 + 20 * np.random.random([4, 17, 73, 144]) latitude = np.linspace(-90., 90., 73) longitude = np.linspace(0., 360., 144, endpoint=False) - pres = ['1000', '925', '850', '700', '600', '500', '400', '300', '250', + press = ['1000', '925', '850', '700', '600', '500', '400', '300', '250', '200', '150', '100', '70', '50', '30', '20', '10'] - level = np.array(pres) + level = np.array(press) level = level.astype(float) * 100 time = np.empty((4)) time[0] = np.datetime64(datetime.datetime(2023, 1, 14, 0)) @@ -1596,9 +1596,9 @@ def test_find_bounding_box_indices(): temperature = 273 + 20 * np.random.random([4, 17, 73, 144]) latitude = np.linspace(-90., 90., 73) longitude = np.linspace(0., 360., 144, endpoint=False) - pres = ['1000', '925', '850', '700', '600', '500', '400', '300', '250', + press = ['1000', '925', '850', '700', '600', '500', '400', '300', '250', '200', '150', '100', '70', '50', '30', '20', '10'] - level = np.array(pres) + level = np.array(press) level = level.astype(float) * 100 time = np.empty((4)) time[0] = np.datetime64(datetime.datetime(2023, 1, 14, 0)) @@ -1626,9 +1626,9 @@ def test_get_vectorized_array_indices(): temperature = 273 + 20 * np.random.random([4, 17, 73, 144]) latitude = np.linspace(-90., 90., 73) longitude = np.linspace(0., 360., 144, endpoint=False) - pres = ['1000', '925', '850', '700', '600', '500', '400', '300', '250', + press = ['1000', '925', '850', '700', '600', '500', '400', '300', '250', '200', '150', '100', '70', '50', '30', '20', '10'] - level = np.array(pres) + level = np.array(press) level = level.astype(float) * 100 time = np.empty((4)) time[0] = np.datetime64(datetime.datetime(2023, 1, 14, 0)) From e7c2fb4e12bb77f091cd89de9f8804becd894dff Mon Sep 17 00:00:00 2001 From: Ashwin Date: Thu, 18 Jul 2024 10:09:11 +0530 Subject: [PATCH 45/51] removed boto3 --- examples/calculations/Vorticity_Divergence_Inversion.py | 9 --------- 1 file changed, 9 deletions(-) diff --git a/examples/calculations/Vorticity_Divergence_Inversion.py b/examples/calculations/Vorticity_Divergence_Inversion.py index 4d41e5a9ec5..4a14fb5cc83 100644 --- a/examples/calculations/Vorticity_Divergence_Inversion.py +++ b/examples/calculations/Vorticity_Divergence_Inversion.py @@ -14,10 +14,7 @@ import os.path import xarray as xr import numpy as np -import boto3 import metpy.calc as mpcalc -from botocore import UNSIGNED -from botocore.config import Config import matplotlib.pyplot as plt from matplotlib.cm import get_cmap import matplotlib.ticker as mticker @@ -25,12 +22,6 @@ from cartopy.feature import NaturalEarthFeature from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER -if (not os.path.isfile('gfs.t12z.pgrb2.0p25.f000')): - - client = boto3.client('s3', config=Config(signature_version=UNSIGNED)) - client.download_file('noaa-gfs-bdp-pds', 'gfs.20230809/12/atmos/gfs.t12z.pgrb2.0p25.f000', - 'gfs.t12z.pgrb2.0p25.f000') - u850 = xr.open_dataset('gfs.t12z.pgrb2.0p25.f000', engine='cfgrib', backend_kwargs={'filter_by_keys': {'typeOfLevel': 'isobaricInhPa', 'shortName': 'u', From 22ccdf50cf4e1b68c79a4881518e5d5cb9a2de0d Mon Sep 17 00:00:00 2001 From: Ashwin Date: Thu, 18 Jul 2024 10:13:31 +0530 Subject: [PATCH 46/51] removed boto3 --- examples/calculations/Vorticity_Divergence_Inversion.py | 1 - 1 file changed, 1 deletion(-) diff --git a/examples/calculations/Vorticity_Divergence_Inversion.py b/examples/calculations/Vorticity_Divergence_Inversion.py index 4a14fb5cc83..1b0dd7ee62f 100644 --- a/examples/calculations/Vorticity_Divergence_Inversion.py +++ b/examples/calculations/Vorticity_Divergence_Inversion.py @@ -11,7 +11,6 @@ This example demonstrates the calculation of reconstructed wind field for cyclone dora and plotting using matplotlib. """ -import os.path import xarray as xr import numpy as np import metpy.calc as mpcalc From f6c567700060a37ecb4172780c825264abe701e7 Mon Sep 17 00:00:00 2001 From: Ashwin Date: Thu, 18 Jul 2024 10:25:06 +0530 Subject: [PATCH 47/51] removed flake8 errors --- src/metpy/calc/tools.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/metpy/calc/tools.py b/src/metpy/calc/tools.py index 5e012d609b8..608d2baae2f 100644 --- a/src/metpy/calc/tools.py +++ b/src/metpy/calc/tools.py @@ -1961,7 +1961,7 @@ def bounding_box_mask(data_array, min_lat, max_lat, min_lon, max_lon): @exporter.export def find_bounding_box_indices(data_mask, min_lat, max_lat, min_lon, max_lon): - """Computes the array indices of a bounding box.""" + """Returns the array indices of a bounding box.""" @dataclass class BoundingBoxIndices: @@ -1979,7 +1979,7 @@ class BoundingBoxIndices: @exporter.export def get_vectorized_array_indices(i_bb_indices): - """function computes the vectorization indices for inner for loop in the + """Returns the vectorization indices for inner for loop in the wind field reconstruction method. """ From 4a059fab3816642613cdca1c469540057c20bd14 Mon Sep 17 00:00:00 2001 From: Ashwin Date: Thu, 18 Jul 2024 14:55:45 +0530 Subject: [PATCH 48/51] added random generator --- tests/calc/test_calc_tools.py | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/tests/calc/test_calc_tools.py b/tests/calc/test_calc_tools.py index 036df423ba4..a9b917198f0 100644 --- a/tests/calc/test_calc_tools.py +++ b/tests/calc/test_calc_tools.py @@ -1565,11 +1565,12 @@ def test_vector_derivative_return_subset(return_only, length): def test_bounding_box_mask(): """ Test the mask of a bounding box. """ - temperature = 273 + 20 * np.random.random([4, 17, 73, 144]) + rng = np.random.default_rng() + temperature = 273 + 20 * rng.random(size=(4, 17, 73, 144)) latitude = np.linspace(-90., 90., 73) longitude = np.linspace(0., 360., 144, endpoint=False) press = ['1000', '925', '850', '700', '600', '500', '400', '300', '250', - '200', '150', '100', '70', '50', '30', '20', '10'] + '200', '150', '100', '70', '50', '30', '20', '10'] level = np.array(press) level = level.astype(float) * 100 time = np.empty((4)) @@ -1593,11 +1594,12 @@ def test_bounding_box_mask(): def test_find_bounding_box_indices(): """Tests the bounding box indices for 2 different cases. """ - temperature = 273 + 20 * np.random.random([4, 17, 73, 144]) + rng = np.random.default_rng() + temperature = 273 + 20 * rng.random(size=(4, 17, 73, 144)) latitude = np.linspace(-90., 90., 73) longitude = np.linspace(0., 360., 144, endpoint=False) press = ['1000', '925', '850', '700', '600', '500', '400', '300', '250', - '200', '150', '100', '70', '50', '30', '20', '10'] + '200', '150', '100', '70', '50', '30', '20', '10'] level = np.array(press) level = level.astype(float) * 100 time = np.empty((4)) @@ -1623,11 +1625,12 @@ def test_find_bounding_box_indices(): def test_get_vectorized_array_indices(): """Tests the vectorized array indices for two different bounding boxes. """ - temperature = 273 + 20 * np.random.random([4, 17, 73, 144]) + rng = np.random.default_rng() + temperature = 273 + 20 * rng.random(size=(4, 17, 73, 144)) latitude = np.linspace(-90., 90., 73) longitude = np.linspace(0., 360., 144, endpoint=False) press = ['1000', '925', '850', '700', '600', '500', '400', '300', '250', - '200', '150', '100', '70', '50', '30', '20', '10'] + '200', '150', '100', '70', '50', '30', '20', '10'] level = np.array(press) level = level.astype(float) * 100 time = np.empty((4)) From afeee6fd27b0a004e58f44f78ff70373223ba9a7 Mon Sep 17 00:00:00 2001 From: Ashwin Date: Thu, 18 Jul 2024 14:59:40 +0530 Subject: [PATCH 49/51] added rotational and divergennt methods --- tests/calc/test_kinematics.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/tests/calc/test_kinematics.py b/tests/calc/test_kinematics.py index f71a75bc530..7e0ab0b3b1b 100644 --- a/tests/calc/test_kinematics.py +++ b/tests/calc/test_kinematics.py @@ -6,7 +6,7 @@ import numpy as np import pytest import xarray as xr - +import sys from metpy.calc import (absolute_vorticity, advection, ageostrophic_wind, coriolis_parameter, divergence, first_derivative, frontogenesis, geospatial_laplacian, geostrophic_wind, inertial_advective_wind, lat_lon_grid_deltas, @@ -14,7 +14,8 @@ potential_vorticity_baroclinic, potential_vorticity_barotropic, q_vector, shearing_deformation, static_stability, storm_relative_helicity, stretching_deformation, total_deformation, - vorticity, wind_components) + vorticity, wind_components,rotational_wind_from_inversion, + divergent_wind_from_inversion) from metpy.constants import g, Re from metpy.testing import (assert_almost_equal, assert_array_almost_equal, assert_array_equal, get_test_data) @@ -70,8 +71,9 @@ def test_vorticity(): def test_vorticity_geographic(geog_data): """Test vorticity for simple case on geographic coordinates.""" crs, lons, lats, u, v, mx, my, dx, dy = geog_data + print(crs) vort = vorticity(u, v, longitude=lons, latitude=lats, crs=crs) - + sys.exit() # Calculate the true field using known map-correct approach truth = (mx * first_derivative(v, delta=dx, axis=1) - my * first_derivative(u, delta=dy, axis=0) From 8f274b5127ce5bfb95bb8b8132cef86c617ecb0f Mon Sep 17 00:00:00 2001 From: Ashwin Date: Thu, 18 Jul 2024 17:17:53 +0530 Subject: [PATCH 50/51] added more comments --- src/metpy/calc/tools.py | 1 - 1 file changed, 1 deletion(-) diff --git a/src/metpy/calc/tools.py b/src/metpy/calc/tools.py index 608d2baae2f..ab0b3488918 100644 --- a/src/metpy/calc/tools.py +++ b/src/metpy/calc/tools.py @@ -1982,7 +1982,6 @@ def get_vectorized_array_indices(i_bb_indices): """Returns the vectorization indices for inner for loop in the wind field reconstruction method. """ - i_x_ll = i_bb_indices.x_ll i_x_ur = i_bb_indices.x_ur i_y_ll = i_bb_indices.y_ll From 78b8a2c76aa0c1af7012a7bdcbf00993cf6358e6 Mon Sep 17 00:00:00 2001 From: Ashwin Date: Thu, 18 Jul 2024 17:19:35 +0530 Subject: [PATCH 51/51] added more comments --- tests/calc/test_calc_tools.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/calc/test_calc_tools.py b/tests/calc/test_calc_tools.py index a9b917198f0..9900763df14 100644 --- a/tests/calc/test_calc_tools.py +++ b/tests/calc/test_calc_tools.py @@ -1573,7 +1573,7 @@ def test_bounding_box_mask(): '200', '150', '100', '70', '50', '30', '20', '10'] level = np.array(press) level = level.astype(float) * 100 - time = np.empty((4)) + time = np.empty(4) time[0] = np.datetime64(datetime.datetime(2023, 1, 14, 0)) time[1] = np.datetime64(datetime.datetime(2023, 1, 14, 6)) time[2] = np.datetime64(datetime.datetime(2023, 1, 14, 12)) @@ -1602,7 +1602,7 @@ def test_find_bounding_box_indices(): '200', '150', '100', '70', '50', '30', '20', '10'] level = np.array(press) level = level.astype(float) * 100 - time = np.empty((4)) + time = np.empty(4) time[0] = np.datetime64(datetime.datetime(2023, 1, 14, 0)) time[1] = np.datetime64(datetime.datetime(2023, 1, 14, 6)) time[2] = np.datetime64(datetime.datetime(2023, 1, 14, 12)) @@ -1633,7 +1633,7 @@ def test_get_vectorized_array_indices(): '200', '150', '100', '70', '50', '30', '20', '10'] level = np.array(press) level = level.astype(float) * 100 - time = np.empty((4)) + time = np.empty(4) time[0] = np.datetime64(datetime.datetime(2023, 1, 14, 0)) time[1] = np.datetime64(datetime.datetime(2023, 1, 14, 6)) time[2] = np.datetime64(datetime.datetime(2023, 1, 14, 12))