Differentiate with the second order accurate central differences. .. note:: This feature is limited to simple cartesian geometry, i.e. coord must be one dimensional. Parameters ---------- coord : Hashable The coordinate to
(
self,
coord: Hashable,
edge_order: Literal[1, 2] = 1,
datetime_unit: DatetimeUnitOptions | None = None,
)
| 8420 | return self._replace(variables, coord_names, attrs=attrs) |
| 8421 | |
| 8422 | def differentiate( |
| 8423 | self, |
| 8424 | coord: Hashable, |
| 8425 | edge_order: Literal[1, 2] = 1, |
| 8426 | datetime_unit: DatetimeUnitOptions | None = None, |
| 8427 | ) -> Self: |
| 8428 | """Differentiate with the second order accurate central |
| 8429 | differences. |
| 8430 | |
| 8431 | .. note:: |
| 8432 | This feature is limited to simple cartesian geometry, i.e. coord |
| 8433 | must be one dimensional. |
| 8434 | |
| 8435 | Parameters |
| 8436 | ---------- |
| 8437 | coord : Hashable |
| 8438 | The coordinate to be used to compute the gradient. |
| 8439 | edge_order : {1, 2}, default: 1 |
| 8440 | N-th order accurate differences at the boundaries. |
| 8441 | datetime_unit : None or {"W", "D", "h", "m", "s", "ms", \ |
| 8442 | "us", "ns", "ps", "fs", "as", None}, default: None |
| 8443 | Unit to compute gradient. Only valid for datetime coordinate. |
| 8444 | |
| 8445 | Returns |
| 8446 | ------- |
| 8447 | differentiated: Dataset |
| 8448 | |
| 8449 | See Also |
| 8450 | -------- |
| 8451 | numpy.gradient: corresponding numpy function |
| 8452 | """ |
| 8453 | if coord not in self.variables and coord not in self.dims: |
| 8454 | variables_and_dims = tuple(set(self.variables.keys()).union(self.dims)) |
| 8455 | raise ValueError( |
| 8456 | f"Coordinate {coord!r} not found in variables or dimensions {variables_and_dims}." |
| 8457 | ) |
| 8458 | |
| 8459 | coord_var = self[coord].variable |
| 8460 | if coord_var.ndim != 1: |
| 8461 | raise ValueError( |
| 8462 | f"Coordinate {coord} must be 1 dimensional but is {coord_var.ndim}" |
| 8463 | " dimensional" |
| 8464 | ) |
| 8465 | |
| 8466 | dim = coord_var.dims[0] |
| 8467 | if _contains_datetime_like_objects(coord_var): |
| 8468 | if coord_var.dtype.kind in "mM" and datetime_unit is None: |
| 8469 | datetime_unit = cast( |
| 8470 | "DatetimeUnitOptions", np.datetime_data(coord_var.dtype)[0] |
| 8471 | ) |
| 8472 | elif datetime_unit is None: |
| 8473 | datetime_unit = "s" # Default to seconds for cftime objects |
| 8474 | coord_var = coord_var._to_numeric(datetime_unit=datetime_unit) |
| 8475 | |
| 8476 | variables = {} |
| 8477 | for k, v in self.variables.items(): |
| 8478 | if k in self.data_vars and dim in v.dims and k not in self.coords: |
| 8479 | if _contains_datetime_like_objects(v): |