(field: Grid)
Computes the divergence of a grid using finite differences.

    This function can operate in two modes depending on the type of `field`:

    * `CenteredGrid` approximates the divergence at cell centers using central differences
    * `StaggeredGrid` exactly computes the divergence at cell centers

    Args:
        field: vector field as `CenteredGrid` or `StaggeredGrid`

    Returns:
        Divergence field as `CenteredGrid`
Computes the divergence of a grid using finite differences.
Computes the divergence of a grid using finite differences .
def divergence(field: Grid) -> CenteredGrid:
    """
    Computes the divergence of a grid using finite differences.

    This function can operate in two modes depending on the type of `field`:

    * `CenteredGrid` approximates the divergence at cell centers using central differences
    * `StaggeredGrid` exactly computes the divergence at cell centers

    Args:
        field: vector field as `CenteredGrid` or `StaggeredGrid`

    Returns:
        Divergence field as `CenteredGrid`
    """
    if isinstance(field, StaggeredGrid):
        field = bake_extrapolation(field)
        components = []
        for i, dim in enumerate(field.shape.spatial.names):
            div_dim = math.spatial_gradient(field.values.vector[i], dx=field.dx[i], difference='forward', padding=None, dims=[dim]).gradient[0]
            components.append(div_dim)
        data = math.sum(components, dim='0')
        return CenteredGrid(data, bounds=field.bounds, extrapolation=field.extrapolation.spatial_gradient())
    elif isinstance(field, CenteredGrid):
        left, right = shift(field, (-1, 1), stack_dim=batch('div_'))
        grad = (right - left) / (field.dx * 2)
        components = [grad.vector[i].div_[i] for i in range(grad.div_.size)]
        result = sum(components)
        return result
    else:
        raise NotImplementedError(f"{type(field)} not supported. Only StaggeredGrid allowed.")
def divergence ( field : Grid ) -> CenteredGrid : if isinstance ( field , StaggeredGrid ) : field = bake_extrapolation ( field ) components = [ ] for i , dim in enumerate ( field . shape . spatial . names ) : div_dim = math . spatial_gradient ( field . values . vector [ i ] , dx = field . dx [ i ] , difference = 'forward' , padding = None , dims = [ dim ] ) . gradient [ 0 ] components . append ( div_dim ) data = math . sum ( components , dim = '0' ) return CenteredGrid ( data , bounds = field . bounds , extrapolation = field . extrapolation . spatial_gradient ( ) ) elif isinstance ( field , CenteredGrid ) : left , right = shift ( field , ( - 1 , 1 ) , stack_dim = batch ( 'div_' ) ) grad = ( right - left ) / ( field . dx * 2 ) components = [ grad . vector [ i ] . div_ [ i ] for i in range ( grad . div_ . size ) ] result = sum ( components ) return result else : raise NotImplementedError ( f"{type(field)} not supported. Only StaggeredGrid allowed." )