Decorate the derivative functions to make them work nicely with DataArrays.

    This will automatically determine if the coordinates can be pulled directly from the
    DataArray, or if a call to lat_lon_grid_deltas is needed.
967163
def xarray_derivative_wrap(func):
    
    @functools.wraps(func)
    def wrapper(f, **kwargs):
        if 'x' in kwargs or 'delta' in kwargs:
            # Use the usual DataArray to pint.Quantity preprocessing wrapper
            return preprocess_xarray(func)(f, **kwargs)
        elif isinstance(f, xr.DataArray):
            # Get axis argument, defaulting to first dimension
            axis = f.metpy.find_axis_name(kwargs.get('axis', 0))

            # Initialize new kwargs with the axis number
            new_kwargs = {'axis': f.get_axis_num(axis)}

            if f[axis].attrs.get('_metpy_axis') == 'T':
                # Time coordinate, need to convert to seconds from datetimes
                new_kwargs['x'] = f[axis].metpy.as_timestamp().metpy.unit_array
            elif CFConventionHandler.check_axis(f[axis], 'lon'):
                # Longitude coordinate, need to get grid deltas
                new_kwargs['delta'], _ = grid_deltas_from_dataarray(f)
            elif CFConventionHandler.check_axis(f[axis], 'lat'):
                # Latitude coordinate, need to get grid deltas
                _, new_kwargs['delta'] = grid_deltas_from_dataarray(f)
            else:
                # General coordinate, use as is
                new_kwargs['x'] = f[axis].metpy.unit_array

            # Calculate and return result as a DataArray
            result = func(f.metpy.unit_array, **new_kwargs)
            return xr.DataArray(result.magnitude,
                                coords=f.coords,
                                dims=f.dims,
                                attrs={'units': str(result.units)})
        else:
            # Error
            raise ValueError('Must specify either "x" or "delta" for value positions when "f" '
                             'is not a DataArray.')
    return wrapper
80825
def _wrapper(func, *vect_args, **vect_kwargs):
        """"""
        if not hasattr(func, '__name__'):
            # Set name if not available. Happens if func is actually a function
            func.__name__ = '{}.__call__'.format(func.__class__.__name__)

        return wraps(func)(_NumpyVectorizeWrapper(func, *vect_args,
                                                  **vect_kwargs))
964512
def _apply_to_data(data, func, unpack_dict=False):
    
    apply_ = partial(_apply_to_data, func=func, unpack_dict=unpack_dict)

    if isinstance(data, dict):
        if unpack_dict:
            return [apply_(v) for v in data.values()]
        return {k: apply_(v) for k, v in data.items()}

    if isinstance(data, (list, tuple)):
        try:
            # e.g.list/tuple of arrays
            return [apply_(x) for x in data]
        except TypeError:
            return func(data)

    return func(data)
1242364
def _process_gradient_args(f, kwargs):
    """"""
    axes = kwargs.get('axes', range(f.ndim))

    def _check_length(positions):
        if 'axes' in kwargs and len(positions) < len(axes):
            raise ValueError('Length of "coordinates" or "deltas" cannot be less than that '
                             'of "axes".')
        elif 'axes' not in kwargs and len(positions) != len(axes):
            raise ValueError('Length of "coordinates" or "deltas" must match the number of '
                             'dimensions of "f" when "axes" is not given.')

    if 'deltas' in kwargs:
        if 'coordinates' in kwargs or 'x' in kwargs:
            raise ValueError('Cannot specify both "coordinates" and "deltas".')
        _check_length(kwargs['deltas'])
        return 'delta', kwargs['deltas'], axes
    elif 'coordinates' in kwargs:
        _check_length(kwargs['coordinates'])
        return 'x', kwargs['coordinates'], axes
    elif 'x' in kwargs:
        warnings.warn('The use of "x" as a parameter for coordinate values has been '
                      'deprecated. Use "coordinates" instead.', metpyDeprecation)
        _check_length(kwargs['x'])
        return 'x', kwargs['x'], axes
    elif isinstance(f, xr.DataArray):
        return 'pass', axes, axes  # only the axis argument matters
    else:
        raise ValueError('Must specify either "coordinates" or "deltas" for value positions '
                         'when "f" is not a DataArray.')
1208542
def derivativeW(self,*args):
        '''
        
        '''
        if self.n_dims >= 4:
            j = 0
        else:
            assert False, "Derivative with respect to W can't be called when n_dims < 4!"
        if self.i_dim == j:
            return np.ones_like(*args[0])
        else:
            return np.zeros_like(*args[0])
1256013
def extend_shapes(df_shapes, axis, distance):
    '''
    
    '''
    df_shapes_i = df_shapes.copy()
    offsets = df_shapes_i[axis + '_center_offset'].copy()
    offsets[offsets < 0] -= distance
    offsets[offsets >= 0] += distance
    df_shapes_i[axis] = df_shapes_i[axis + '_center'] + offsets
    return df_shapes_i
745074
def data_structure_builder(func):
    
    @wraps(func)
    def ds_builder_wrapper(function, *args, **kwargs):
        try:
            function = DSBuilder(function)
        except NoBuilder:
            pass
        return func(function, *args, **kwargs)

    return ds_builder_wrapper
42414
def row_coordinates(self, X):
        """"""
        utils.validation.check_is_fitted(self, 'V_')

        _, row_names, _, _ = util.make_labels_and_names(X)

        if isinstance(X, pd.SparseDataFrame):
            X = X.to_coo().astype(float)
        elif isinstance(X, pd.DataFrame):
            X = X.to_numpy()

        if self.copy:
            X = X.copy()

        # Normalise the rows so that they sum up to 1
        if isinstance(X, np.ndarray):
            X = X / X.sum(axis=1)[:, None]
        else:
            X = X / X.sum(axis=1)

        return pd.DataFrame(
            data=X @ sparse.diags(self.col_masses_.to_numpy() ** -0.5) @ self.V_.T,
            index=row_names
        )
291312
def apply(self, func, axis, *args, **kwargs):
        
        if callable(func):
            return self._callable_func(func, axis, *args, **kwargs)
        elif isinstance(func, dict):
            return self._dict_func(func, axis, *args, **kwargs)
        elif is_list_like(func):
            return self._list_like_func(func, axis, *args, **kwargs)
        else:
            pass
1330341
function buildAxis(){
            let minor, major;

            if (xAxisFormat === 'custom' && typeof xAxisCustomFormat === 'string') {
                minor = {
                    tick: xTicks,
                    format: d3TimeFormat.timeFormat(xAxisCustomFormat)
                };
            } else {
                ({minor, major} = timeAxisHelper.getTimeSeriesAxis(data, width, xAxisFormat));
            }

            xAxis = d3Axis.axisBottom(xScale)
                .ticks(minor.tick)
                .tickSize(10, 0)
                .tickPadding([tickPadding])
                .tickFormat(minor.format);
        }
1101950
function (coordsArr) {
      function mapProp(func, array, prop) {
        function getProp(el) {
          return el[prop];
        }

        if (Array.prototype.map) {
          return func.apply(Math, array.map(getProp));
        }
        return func.apply(Math, $.map(array, getProp));
      }

      return {
        TL: {
          row: mapProp(Math.min, coordsArr, "row"),
          col: mapProp(Math.min, coordsArr, "col")
        },
        BR: {
          row: mapProp(Math.max, coordsArr, "row"),
          col: mapProp(Math.max, coordsArr, "col")
        }
      };
    }
1355951
def dxyz2dlonlat(x,y,z, dfx, dfy, dfz):
    

    xs = np.array(x)
    ys = np.array(y)
    zs = np.array(z)

    lons = np.arctan2(ys, xs)
    lats = np.arcsin(zs)

    dfxs = np.array(dfx)
    dfys = np.array(dfy)
    dfzs = np.array(dfz)

    dlon = -dfxs * np.cos(lats) * np.sin(lons) + dfys * np.cos(lats) * np.cos(lons) # no z dependence
    dlat = -dfxs * np.sin(lats) * np.cos(lons) - dfys * np.sin(lats) * np.sin(lons) + dfzs * np.cos(lats)

    corr = np.sqrt((1.0-zs**2))
    valid = ~np.isclose(corr,0.0)

    dlon[valid] = dlon[valid] / corr[valid]

    return dlon, dlat
1186168
def add(x, y, context=None):
    
    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_add,
        (
            BigFloat._implicit_convert(x),
            BigFloat._implicit_convert(y),
        ),
        context,
    )
464194
def coordinates_present?(*args)
      args.each do |a|
        # note that Float::NAN != Float::NAN
        # still, this could probably be improved:
        return false if (!a.is_a?(Numeric) or a.to_s == "NaN")
      end
      true
    end
1115328
def _default_in_place(func, x, out, **kwargs):
    """"""
    result = np.array(func._call_out_of_place(x, **kwargs), copy=False)
    if result.dtype == object:
        # Different shapes encountered, need to broadcast
        flat_results = result.ravel()
        if is_valid_input_array(x, func.domain.ndim):
            scalar_out_shape = out_shape_from_array(x)
        elif is_valid_input_meshgrid(x, func.domain.ndim):
            scalar_out_shape = out_shape_from_meshgrid(x)
        else:
            raise RuntimeError('bad input')

        bcast_results = [np.broadcast_to(res, scalar_out_shape)
                         for res in flat_results]
        # New array that is flat in the `out_shape` axes, reshape it
        # to the final `out_shape + scalar_shape`, using the same
        # order ('C') as the initial `result.ravel()`.
        result = np.array(bcast_results, dtype=func.scalar_out_dtype)
        result = result.reshape(func.out_shape + scalar_out_shape)

    # The following code is required to remove extra axes, e.g., when
    # the result has shape (2, 1, 3) but should have shape (2, 3).
    # For those cases, broadcasting doesn't apply.
    try:
        reshaped = result.reshape(out.shape)
    except ValueError:
        # This is the case when `result` must be broadcast
        out[:] = result
    else:
        out[:] = reshaped

    return out
1023457
def row_coordinates(self, X):
        """"""
        utils.validation.check_is_fitted(self, 's_')

        # Check input
        if self.check_input:
            utils.check_array(X, dtype=[str, np.number])

        # Prepare input
        X = self._prepare_input(X)

        return self._row_coordinates_from_global(self._build_X_global(X))
1172902
def _transform_coordinates(
            self,
            func: Callable[[Union[int, float], Union[int, float]],
                           Tuple[Union[int, float], Union[int, float]]]
    ) -> None:
        """"""

        def func_x(x: Union[int, float]) -> Union[int, float]:
            return func(x, 0)[0]

        def func_y(y: Union[int, float]) -> Union[int, float]:
            return func(0, y)[1]

        self.entries = {
            cast(Tuple[int, int], func(int(x), int(y))): v
            for (x, y), v in self.entries.items()
        }
        self.vertical_lines = [
            _VerticalLine(func_x(x), func_y(y1), func_y(y2), emph)
            for x, y1, y2, emph in self.vertical_lines]
        self.horizontal_lines = [
            _HorizontalLine(func_y(y), func_x(x1), func_x(x2), emph)
            for y, x1, x2, emph in self.horizontal_lines]
        self.horizontal_padding = {
            int(func_x(int(x))): padding
            for x, padding in self.horizontal_padding.items()
        }
        self.vertical_padding = {
            int(func_y(int(y))): padding
            for y, padding in self.vertical_padding.items()
        }