Skip to content

Commit

Permalink
ADD: Add add_field_like method to xradar (#1718)
Browse files Browse the repository at this point in the history
  • Loading branch information
mgrover1 authored Jan 8, 2025
1 parent 78a12bd commit 37807ad
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
45 changes: 45 additions & 0 deletions pyart/xradar/accessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -494,6 +494,51 @@ def add_field(self, field_name, dic, replace_existing=False):
self.xradar[f"sweep_{sweep}"].ds = sweep_ds
return

def add_field_like(
self, existing_field_name, field_name, data, replace_existing=False
):
"""
Add a field to the object with metadata from a existing field.
Note that the data parameter is not copied by this method.
If data refers to a 'data' array from an existing field dictionary, a
copy should be made within or prior to using this method. If this is
not done the 'data' key in both field dictionaries will point to the
same NumPy array and modification of one will change the second. To
copy NumPy arrays use the copy() method. See the Examples section
for how to create a copy of the 'reflectivity' field as a field named
'reflectivity_copy'.
Parameters
----------
existing_field_name : str
Name of an existing field to take metadata from when adding
the new field to the object.
field_name : str
Name of the field to add to the dictionary of fields.
data : array
Field data. A copy of this data is not made, see the note above.
replace_existing : bool, optional
True to replace the existing field with key field_name if it
exists, loosing any existing data. False will raise a ValueError
when the field already exists.
Examples
--------
>>> radar.add_field_like('reflectivity', 'reflectivity_copy',
... radar.fields['reflectivity']['data'].copy())
"""
if existing_field_name not in self.fields:
err = f"field {existing_field_name} does not exist in object"
raise ValueError(err)
dic = {}
for k, v in self.fields[existing_field_name].items():
if k != "data":
dic[k] = v
dic["data"] = data
return self.add_field(field_name, dic, replace_existing=replace_existing)

def get_field(self, sweep, field_name, copy=False):
"""
Return the field data for a given sweep.
Expand Down
5 changes: 5 additions & 0 deletions tests/xradar/test_accessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,11 @@ def test_add_field(filename=filename):
radar.add_field("reflectivity", new_field)
assert "reflectivity" in radar.fields
assert radar["sweep_0"]["reflectivity"].shape == radar["sweep_0"]["DBZ"].shape
# Test add field like as well
radar.add_field_like("reflectivity", "test", new_field["data"])
assert "test" in radar.fields
assert "data" in radar.fields["test"]
assert radar.fields["test"]["units"] == "dBZ"


def test_grid(filename=filename):
Expand Down

0 comments on commit 37807ad

Please sign in to comment.