fields.mixins.dense_mathops.DenseTensorFieldDMOMixin.gradient#

DenseTensorFieldDMOMixin.gradient(basis: Literal['contravariant', 'covariant'] | None = 'covariant', inverse_metric_field: _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str] | None = None, out: _Buffer | _SupportsArray[dtype[Any]] | _NestedSequence[_SupportsArray[dtype[Any]]] | complex | bytes | str | _NestedSequence[complex | bytes | str] | None = None, *, output_axes: Sequence[str] | None = None, as_array: bool = False, buffer_class: Type[BufferBase] | None = None, buffer_registry: BufferRegistry | None = None, buffer_args: Sequence[Any] | None = None, buffer_kwargs: Dict | None = None, **kwargs)[source]#

Compute the covariant or contravariant gradient of this field.

This method computes the coordinate-wise gradient of the field, applied independently to each scalar component. The result is a new tensor field whose rank is one greater than that of the input, with the final axis encoding the derivative direction (covariant or contravariant).

\[\phi \mapsto \nabla_\mu \phi \quad \text{or} \quad \nabla^\mu \phi\]

The gradient basis is selected using the basis argument. In covariant form, the gradient consists of raw partial derivatives. In contravariant form, the derivatives are raised using the inverse metric tensor \(g^{\mu\nu}\).

Hint

This is a wrapper around dense_gradient(), which in turn dispatches to either dense_gradient_covariant() or dense_gradient_contravariant_full().

Parameters:
  • basis ({'covariant', 'contravariant'}, optional) –

    The basis in which to compute the gradient. Defaults to 'covariant'.

    • If 'covariant': returns raw partial derivatives \(\partial_\mu \phi\)

    • If 'contravariant': raises the result using \(g^{\mu\nu}\) to produce \(\nabla^\mu \phi\)

  • inverse_metric_field (array-like, optional) –

    The inverse metric tensor \(g^{\mu\nu}\) required for computing the contravariant gradient.

    • For diagonal metrics: shape (*spatial_shape, ndim)

    • For full metrics: shape (*spatial_shape, ndim, ndim)

    If not provided, it is computed automatically from the coordinate system. Ignored when basis='covariant'.

  • out (array-like, optional) – An optional buffer in which to store the result. This can be used to reduce memory usage when performing computations. The shape of out must be compliant with broadcasting rules (see Notes). out may be a buffer or any other array-like object.

  • output_axes (list of str, optional) –

    The axes of the coordinate system over which the result should span. By default, the dependence is calculated internally.

    This argument may be specified to expand the number of axes onto which the output field is computed. output_axes must be a superset of the axes of the calling field.

  • in_chunks (bool, default False) – If True, compute the result in streaming fashion over grid chunks to reduce memory usage.

  • pbar (bool, default True) – Show a progress bar during chunked computation.

  • pbar_kwargs (dict, optional) – Extra keyword arguments passed to the progress bar (e.g., desc or position).

  • as_array (bool, default False) – If True, return the raw array representing the result. If False, return a new symbolic field with the raised index.

  • buffer_class (type, optional) –

    Class to use when wrapping the result buffer, e.g., fields.buffers.core.ArrayBuffer or fields.buffers.core.UnytArrayBuffer.

    Defaults to buffer resolution to determine a fitting buffer for the resulting array result.

  • buffer_registry (BufferRegistry, optional) – Registry to use when resolving the buffer class. Required for advanced dispatch.

  • buffer_args (Sequence, optional) – Positional arguments forwarded to the buffer constructor.

  • buffer_kwargs (dict, optional) – Keyword arguments forwarded to the buffer constructor.

Returns:

The gradient of the field. The output shape matches the input shape with one additional trailing axis of size ndim.

  • If as_array=False (default), returns a new DenseTensorField instance.

  • If as_array=True, returns a NumPy array of shape:

    (grid_shape over output_axes, ..., element_shape, ndim)
    

Return type:

DenseTensorField or ndarray

Notes

Output Shape and Signature

The gradient adds one additional index to the tensor field:

  • For a scalar field, the output becomes a vector field.

  • For a vector field, the output becomes a rank-2 tensor.

The updated element shape is the original field’s element_shape extended by (ndim,).

The gradient basis determines the signature of this final axis:

  • 'covariant' → covariant index (e.g., ∂μ)

  • 'contravariant' → contravariant index (e.g., ∇^μ)

Metric Requirements

The inverse metric field is only required when basis='contravariant'. If not provided, it is evaluated from the coordinate system automatically.

Chunked Evaluation

When in_chunks=True, the operation is evaluated block-by-block. Ghost cells (1-cell halo) are added to preserve the accuracy of finite-difference stencils.

This is especially useful for HDF5-backed buffers or streaming workloads.

See also

dense_gradient

Grid-level implementation used here.

dense_gradient_covariant

Covariant gradient kernel (raw partial derivatives).

dense_gradient_contravariant_full

Contravariant gradient kernel (full metric).

dense_gradient_contravariant_diag

Contravariant gradient kernel (diagonal metric).