Example on retrieving and plotting winds#

This is a simple example for how to retrieve and plot winds from 2 radars using PyDDA.

Author: Robert C. Jackson

import pydda
from matplotlib import pyplot as plt

berr_grid = pydda.io.read_grid(pydda.tests.EXAMPLE_RADAR0)
cpol_grid = pydda.io.read_grid(pydda.tests.EXAMPLE_RADAR1)

# Load sounding data and insert as an intialization
berr_grid = pydda.initialization.make_constant_wind_field(
    berr_grid, (0.0, 0.0, 0.0), vel_field="corrected_velocity"
)

# Start the wind retrieval. This example only uses the mass continuity
# and data weighting constraints.
Grids, _ = pydda.retrieval.get_dd_wind_field(
    [berr_grid, cpol_grid],
    Co=1.0,
    Cm=256.0,
    Cx=0.0,
    Cy=0.0,
    Cz=0.0,
    Cb=0.0,
    frz=5000.0,
    filter_window=5,
    mask_outside_opt=True,
    upper_bc=1,
    wind_tol=0.5,
    engine="scipy",
    parallel=False,
)

# Plot a horizontal cross section
plt.figure(figsize=(9, 9))
pydda.vis.plot_horiz_xsection_barbs(
    Grids,
    background_field="reflectivity",
    level=6,
    w_vel_contours=[5, 10, 15],
    barb_spacing_x_km=5.0,
    barb_spacing_y_km=15.0,
    vmin=0,
    vmax=70,
)
plt.show()

# Plot a vertical X-Z cross section
plt.figure(figsize=(9, 9))
pydda.vis.plot_xz_xsection_barbs(
    Grids,
    background_field="reflectivity",
    level=40,
    w_vel_contours=[5, 10, 15],
    barb_spacing_x_km=10.0,
    barb_spacing_z_km=2.0,
    vmin=0,
    vmax=70,
)
plt.show()

# Plot a vertical Y-Z cross section
plt.figure(figsize=(9, 9))
pydda.vis.plot_yz_xsection_barbs(
    Grids,
    background_field="reflectivity",
    level=40,
    barb_spacing_y_km=10.0,
    barb_spacing_z_km=2.0,
    vmin=0,
    vmax=70,
)
plt.show()
## You are using the Python ARM Radar Toolkit (Py-ART), an open source
## library for working with weather radar data. Py-ART is partly
## supported by the U.S. Department of Energy as part of the Atmospheric
## Radiation Measurement (ARM) Climate Research Facility, an Office of
## Science user facility.
##
## If you use this software to prepare a publication, please cite:
##
##     JJ Helmus and SM Collis, JORS 2016, doi: 10.5334/jors.119
Welcome to PyDDA 2.4.1
If you are using PyDDA in your publications, please cite:
Jackson et al. (2020) Journal of Open Research Science
Detecting Jax...
Jax/JaxOpt are not installed on your system, unable to use Jax engine.
Detecting TensorFlow...
Unable to load both TensorFlow and tensorflow-probability. TensorFlow engine disabled.
No module named 'tensorflow'
False
Calculating weights for radars 0 and 1
Calculating weights for radars 1 and 0
Calculating weights for models...
Starting solver 
rmsVR = 6.827303971100176
Total points: 81194
The max of w_init is 0.0
Total number of model points: 0
Nfeval | Jvel    | Jmass   | Jsmooth |   Jbg   | Jvort   | Jmodel  | Jpoint  | Max w  
      0|83859.8222|   0.0000|   0.0000|   0.0000|   0.0000|   0.0000|   0.0000|   0.0000
The gradient of the cost functions is 0.6631357968996351
Nfeval | Jvel    | Jmass   | Jsmooth |   Jbg   | Jvort   | Jmodel  | Jpoint  | Max w  
     10|   1.8782|  41.0864|   0.0000|   0.0000|   0.0000|   0.0000|   0.0000|  11.3085
Max change in w: 10.561
The gradient of the cost functions is 0.13750649771707754
Nfeval | Jvel    | Jmass   | Jsmooth |   Jbg   | Jvort   | Jmodel  | Jpoint  | Max w  
     20|   0.3524|  18.6065|   0.0000|   0.0000|   0.0000|   0.0000|   0.0000|  11.8823
Max change in w: 6.008
The gradient of the cost functions is 0.09828068193834624
Nfeval | Jvel    | Jmass   | Jsmooth |   Jbg   | Jvort   | Jmodel  | Jpoint  | Max w  
     30|   0.1953|  10.8039|   0.0000|   0.0000|   0.0000|   0.0000|   0.0000|  12.4880
Max change in w: 4.003
The gradient of the cost functions is 0.09730430370872419
Nfeval | Jvel    | Jmass   | Jsmooth |   Jbg   | Jvort   | Jmodel  | Jpoint  | Max w  
     40|   0.1245|   7.0774|   0.0000|   0.0000|   0.0000|   0.0000|   0.0000|  16.4854
Max change in w: 5.381
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
Cell In[1], line 14
     10 )
     11 
     12 # Start the wind retrieval. This example only uses the mass continuity
     13 # and data weighting constraints.
---> 14 Grids, _ = pydda.retrieval.get_dd_wind_field(
     15     [berr_grid, cpol_grid],
     16     Co=1.0,
     17     Cm=256.0,

File ~/work/PyDDA/PyDDA/pydda/retrieval/wind_retrieve.py:1502, in get_dd_wind_field(Grids, u_init, v_init, w_init, engine, **kwargs)
   1495     w_init = new_grids[0]["w"].values.squeeze()
   1497 if (
   1498     engine.lower() == "scipy"
   1499     or engine.lower() == "jax"
   1500     or engine.lower() == "auglag"
   1501 ):
-> 1502     return _get_dd_wind_field_scipy(
   1503         new_grids, u_init, v_init, w_init, engine, **kwargs
   1504     )
   1505 elif engine.lower() == "tensorflow":
   1506     return _get_dd_wind_field_tensorflow(
   1507         new_grids, u_init, v_init, w_init, **kwargs
   1508     )

File ~/work/PyDDA/PyDDA/pydda/retrieval/wind_retrieve.py:614, in _get_dd_wind_field_scipy(Grids, u_init, v_init, w_init, engine, points, vel_name, refl_field, u_back, v_back, z_back, frz, Co, Cm, Cx, Cy, Cz, Cb, Cv, Cmod, Cpoint, cvtol, gtol, Jveltol, Ut, Vt, low_pass_filter, mask_outside_opt, weights_obs, weights_model, weights_bg, max_iterations, mask_w_outside_opt, filter_window, filter_order, min_bca, max_bca, upper_bc, model_fields, output_cost_functions, roi, wind_tol, tolerance, const_boundary_cond, max_wind_mag, parallel)
    612 parameters.print_out = False
    613 if engine.lower() == "scipy":
--> 614     winds = fmin_l_bfgs_b(
    615         J_function,
    616         winds,
    617         args=(parameters,),
    618         maxiter=max_iterations,
    619         pgtol=tolerance,
    620         bounds=bounds,
    621         fprime=grad_J,
    622         callback=_vert_velocity_callback,
    623     )
    624 else:
    626     def loss_and_gradient(x):

File /usr/share/miniconda/envs/pydda-docs/lib/python3.14/site-packages/scipy/optimize/_lbfgsb_py.py:281, in fmin_l_bfgs_b(func, x0, fprime, args, approx_grad, bounds, m, factr, pgtol, epsilon, iprint, maxfun, maxiter, disp, callback, maxls)
    269 callback = _wrap_callback(callback)
    270 opts = {'disp': disp,
    271         'iprint': iprint,
    272         'maxcor': m,
   (...)    278         'callback': callback,
    279         'maxls': maxls}
--> 281 res = _minimize_lbfgsb(fun, x0, args=args, jac=jac, bounds=bounds,
    282                        **opts)
    283 d = {'grad': res['jac'],
    284      'task': res['message'],
    285      'funcalls': res['nfev'],
    286      'nit': res['nit'],
    287      'warnflag': res['status']}
    288 f = res['fun']

File /usr/share/miniconda/envs/pydda-docs/lib/python3.14/site-packages/scipy/optimize/_lbfgsb_py.py:469, in _minimize_lbfgsb(fun, x0, args, jac, bounds, disp, maxcor, ftol, gtol, eps, maxfun, maxiter, iprint, callback, maxls, finite_diff_rel_step, workers, **unknown_options)
    461 _lbfgsb.setulb(m, x, low_bnd, upper_bnd, nbd, f, g, factr, pgtol, wa,
    462                iwa, task, lsave, isave, dsave, maxls, ln_task)
    464 if task[0] == 3:
    465     # The minimization routine wants f and g at the current x.
    466     # Note that interruptions due to maxfun are postponed
    467     # until the completion of the current minimization iteration.
    468     # Overwrite f and g:
--> 469     f, g = func_and_grad(x)
    470 elif task[0] == 1:
    471     # new iteration
    472     n_iterations += 1

File /usr/share/miniconda/envs/pydda-docs/lib/python3.14/site-packages/scipy/optimize/_differentiable_functions.py:412, in ScalarFunction.fun_and_grad(self, x)
    410 if not np.array_equal(x, self.x):
    411     self._update_x(x)
--> 412 self._update_fun()
    413 self._update_grad()
    414 return self.f, self.g

File /usr/share/miniconda/envs/pydda-docs/lib/python3.14/site-packages/scipy/optimize/_differentiable_functions.py:362, in ScalarFunction._update_fun(self)
    360 def _update_fun(self):
    361     if not self.f_updated:
--> 362         fx = self._wrapped_fun(self.x)
    363         self._nfev += 1
    364         if fx < self._lowest_f:

File /usr/share/miniconda/envs/pydda-docs/lib/python3.14/site-packages/scipy/_lib/_util.py:603, in _ScalarFunctionWrapper.__call__(self, x)
    600 def __call__(self, x):
    601     # Send a copy because the user may overwrite it.
    602     # The user of this class might want `x` to remain unchanged.
--> 603     fx = self.f(np.copy(x), *self.args)
    604     self.nfev += 1
    606     # Make sure the function returns a true scalar

File ~/work/PyDDA/PyDDA/pydda/cost_functions/cost_functions.py:193, in J_function(winds, parameters)
    189 # print("apples Jvel", Jvel)
    191 if parameters.Cm > 0:
    192     # Had to change to float because Jax returns device array (use np.float_())
--> 193     Jmass = _cost_functions_numpy.calculate_mass_continuity(
    194         winds[0],
    195         winds[1],
    196         winds[2],
    197         parameters.z,
    198         parameters.dx,
    199         parameters.dy,
    200         parameters.dz,
    201         coeff=parameters.Cm,
    202     )
    203 else:
    204     Jmass = 0

File ~/work/PyDDA/PyDDA/pydda/cost_functions/_cost_functions_numpy.py:454, in calculate_mass_continuity(u, v, w, z, dx, dy, dz, coeff, anel)
    451     anel_term = np.zeros(w.shape)
    452 div = dudx + dvdy + dwdz + anel_term
--> 454 return coeff * np.sum(np.square(div)) / 2.0

KeyboardInterrupt: