Learn R Programming

vectorialcalculus (version 1.0.5)

gradient_direction2d: Animate gradient and directional derivative on level curves (2D)

Description

Produces a Plotly animation showing level curves of a scalar field together with the gradient direction at a point and a rotating unit direction vector. The directional derivative value is displayed on screen for each frame. A highlight is shown when the rotating direction aligns with the gradient, which corresponds to the maximum directional derivative.

Usage

gradient_direction2d(
  f,
  x0,
  y0,
  xlim,
  ylim,
  n_grid = 70L,
  theta_vals = NULL,
  h = 1e-04,
  arrow_scale = NULL,
  frame_ms = 220L,
  transition_ms = 220L,
  title = NULL,
  safe_mode = TRUE,
  align_tol = 0.08
)

Value

A plotly object (htmlwidget) with animation frames.

Arguments

f

Function. A real-valued function f(x,y). It must accept two numeric arguments and return numeric values.

x0

Numeric scalar. x-coordinate of the base point.

y0

Numeric scalar. y-coordinate of the base point.

xlim

Numeric vector of length 2. Range for x in the contour plot.

ylim

Numeric vector of length 2. Range for y in the contour plot.

n_grid

Integer. Grid size per axis for the contour computation.

theta_vals

Numeric vector. Angles (radians) used as frames. If NULL, a default sequence from 0 to 2*pi is used.

h

Numeric scalar. Step size for central differences.

arrow_scale

Numeric scalar. Scale factor for drawing arrows. If NULL, an automatic scale based on the plot window is used.

frame_ms

Integer. Frame duration in milliseconds.

transition_ms

Integer. Transition duration in milliseconds.

title

Character. Plot title. If NULL, a default title is used.

safe_mode

Logical. If TRUE, use calmer animation defaults intended to reduce flicker and visual stress.

align_tol

Numeric scalar. Angular tolerance (radians) used to decide when the rotating direction is considered aligned with the gradient.

Details

The scalar field is $$ z = f(x,y). $$ At the point $$ (x_0,y_0), $$ the gradient vector is $$ \nabla f(x_0,y_0) = \left(\frac{\partial f}{\partial x}(x_0,y_0), \frac{\partial f}{\partial y}(x_0,y_0)\right). $$ For a unit direction $$ \mathbf{u}(\theta) = (\cos\theta,\sin\theta), $$ the directional derivative is $$ D_{\mathbf{u}} f(x_0,y_0) = \nabla f(x_0,y_0)\cdot \mathbf{u}(\theta). $$ The maximum value over unit directions is $$ \max_{\|\mathbf{u}\|=1} D_{\mathbf{u}} f(x_0,y_0) = \|\nabla f(x_0,y_0)\|, $$ and it occurs when $$ \mathbf{u}(\theta) $$ points in the same direction as $$ \nabla f(x_0,y_0). $$

Partial derivatives are approximated numerically by central differences.

Examples

Run this code
# \donttest{
library(plotly)

f <- function(x, y) x^2 + 2*y^2
gradient_direction2d(
  f = f,
  x0 = 0.6,
  y0 = 0.4,
  xlim = c(-1.5, 1.5),
  ylim = c(-1.5, 1.5),
  safe_mode = TRUE,
  align_tol = 0.06
)
# }

Run the code above in your browser using DataLab