Package {vectorialcalculus}


Type: Package
Title: Numerical Tools for University Calculus
Version: 2.0.0
Description: Independent reconstruction of numerical tools for teaching university calculus. Provides finite difference derivative approximations with numerical sensitivity diagnostics and local linear models. Optional interactive graphics illustrate secants, tangents, differentials and numerical Taylor polynomials of orders one and two. Includes finite limit probes, critical-point and concavity analysis, and Newton iteration with explicit numerical diagnostics. Provides signed Riemann sums, partition refinement, fixed and adaptive quadrature with error diagnostics, and optional interactive illustrations of numerical integration. Evaluates accumulation functions and compares their numerical derivatives with integrands while retaining quadrature and sensitivity diagnostics. Computes geometric areas, graph lengths, revolution volumes and surface areas, with separate interactive region and solid illustrations. Approximates coordinate partials, gradients and line-restriction directional derivatives without inferring total differentiability from finite coordinate probes. Provides candidate affine models and total differentials with actual-change comparisons and separate plane, section and tangent illustrations. Supports rectangular Jacobians, direct Hessian stencils and matrix refinement views with entry-level numerical sensitivity and roundoff diagnostics. Searches for multivariable stationary candidates with explicit starts, retained evaluation histories and conditional second derivative classifications. Solves square nonlinear systems with Newton iteration, Jacobian diagnostics, optional step damping and independent zero-contour playback. Assesses equality-constrained candidates using Lagrange multipliers, numerical rank and conditional tangent-space curvature diagnostics. Integrates Cartesian type I and II regions with nested fixed quadrature, retained inner diagnostics and independent sampled-domain graphics. Supports polar regions with a radial Jacobian and Cartesian domain views. Integrates nested Cartesian solids in six coordinate orders, retaining slice diagnostics with independent fiber and base-projection displays. Supports cylindrical-coordinate solids with a radial Jacobian and separate Cartesian fiber and polar-base views. Spherical regions use explicit azimuth, polar angle and radius with their volume Jacobian and an independent Cartesian radial-fiber display. Assesses implicit related rates with feasibility, differentiability hypotheses, denominator sensitivity diagnostics and a separate local velocity display. Provides product partitions, signed double Riemann sample rules, sampled cell statistics, explicit domain indicators, refinement tables and prism views. Samples standalone planar regions with reusable strip grids and separate filled-domain or horizontal-plate displays. Samples six faces of nested Cartesian solids with shared endpoints and independent face/wireframe displays, without coupling geometric sampling to quadrature. Maps stored cylindrical parameter patches into Cartesian walls, caps and angular cuts with explicit seam and axis-degeneracy limitations. Samples spherical radial shells and angular cuts with explicit pole/origin degeneracies and separate stored-face displays. Shows stored stationary candidates on sampled scalar graphs without rerunning search or classification. Samples spatial parametric curves, displays stored samples, and integrates speed using supplied velocities or numerical Jacobians. Computes spatial Frenet directions, curvature and signed torsion with derivative diagnostics and displays stored results. Samples osculating circles and ribbons with explicit geometry gaps and separate interactive views. Samples spatial vector fields, estimates divergence and curl, and integrates streamlines or time-dependent pathlines with fixed-step Runge-Kutta. Computes signed scalar line integrals and oriented vector work in two and three dimensions, with separate quadrature and derivative diagnostics. Samples parametric and ruled surfaces and integrates scalar densities, area and oriented flux over rectangular parameter domains. Compares the two integrals in Green's circulation theorem over a planar strip and in Stokes' theorem over a rectangular parameter patch. Compares outward flux and integrated divergence over a Cartesian box.
License: MIT + file LICENSE
Depends: R (≥ 4.1.0)
Imports: stats
Suggests: testthat (≥ 3.0.0), plotly
Config/testthat/edition: 3
Encoding: UTF-8
Config/roxygen2/version: 8.1.0
Author: Julio Lizarazo Osorio [aut], Julian Mauricio Fajardo [aut, cre]
Maintainer: Julian Mauricio Fajardo <julian.fajardo1908@gmail.com>
URL: https://github.com/JulianFajardo1908/vectorialcalculus
BugReports: https://github.com/JulianFajardo1908/vectorialcalculus/issues
NeedsCompilation: no
Packaged: 2026-11-10 00:39:40 UTC; LENOVO
Repository: CRAN
Date/Publication: 2026-11-10 09:30:08 UTC

Evaluate a signed accumulation function

Description

Evaluate a signed accumulation function

Usage

vc_accumulation(
  f,
  x,
  lower = 0,
  method = c("adaptive", "trapezoid", "simpson"),
  n = 32L,
  abs_tol = 1e-08,
  rel_tol = 1e-08,
  subdivisions = 100L
)

Arguments

f

Deterministic function accepting a real scalar and returning one finite real scalar. Vectorization is not required.

x

Nonempty finite real vector of upper limits. Input order and duplicates are retained; limits below lower reverse orientation.

lower

Finite real scalar fixed lower integration limit.

method

Quadrature rule: trapezoid, Simpson, or adaptive QUADPACK through stats::integrate(). Improper infinite bounds are not supported.

n

Initial number of equal cells for fixed rules; positive integer, even and at least two for Simpson. Ignored by the adaptive rule.

abs_tol, rel_tol

Nonnegative finite absolute and relative diagnostic tolerances; at least one must be positive. Adaptive integration also applies the tolerance restrictions of stats::integrate().

subdivisions

Positive integer maximum adaptive subinterval count; ignored by fixed rules.

Details

Evaluates A(x) = integral from lower to x of f(t) dt independently at each upper limit; it does not accumulate rounding error along a grid. Equal limits use the integral engine's zero-interval convention. Each integral retains its diagnostics; a returned finite estimate need not satisfy the numerical tolerance. These are signed integrals, not geometric areas. Finite quadrature cannot prove integrability. Split known singularities/discontinuities as appropriate; infinite bounds are absent.

Value

Plain list with type, lower, method, table (x, estimate, error_estimate, tolerance_met, status), results (full vc_integrate objects, one per x) and note.

Examples

(function(x)x^2) |> vc_accumulation(x=c(-1,0,1,2),lower=0)

Approximate the length of a graph

Description

Approximate the length of a graph

Usage

vc_arc_length(
  f,
  interval,
  df = NULL,
  h = NULL,
  breaks = NULL,
  method = c("adaptive", "trapezoid", "simpson"),
  n = 32L,
  abs_tol = 1e-08,
  rel_tol = 1e-08,
  subdivisions = 100L
)

Arguments

f

Deterministic function accepting a real scalar and returning one finite real scalar. Vectorization is not required.

interval

Two finite real bounds, allowing reversed or equal bounds.

df

Optional scalar derivative function, assumed mathematically correct. NULL reuses vc_derivative() with central differences.

h

Optional positive finite numerical derivative step.

breaks

Optional finite strictly increasing interior integration split points, for example known intersections. These are not found automatically.

method

Quadrature rule: trapezoid, Simpson, or adaptive QUADPACK through stats::integrate(). Improper infinite bounds are not supported.

n

Initial number of equal cells for fixed rules; positive integer, even and at least two for Simpson. Ignored by the adaptive rule.

abs_tol, rel_tol

Nonnegative finite absolute and relative diagnostic tolerances; at least one must be positive. Adaptive integration also applies the tolerance restrictions of stats::integrate().

subdivisions

Positive integer maximum adaptive subinterval count; ignored by fixed rules.

Details

Integrates ⁠sqrt(1+f'(t)^2)⁠ for a rectifiable graph. Known corners can be supplied as breaks. Central numerical stencils may leave the domain near endpoints or cross corners; supply df where appropriate. Nonfinite sampled derivatives are errors. Failed sensitivity flags remain visible even if quadrature meets its tolerance. A supplied df is not verified. Quadrature error estimates do not include numerical derivative error; derivative_sensitivity_ok is a separate heuristic, not a bound.

Value

Plain list with type, sorted interval, breaks, method, estimate, integral (full quadrature diagnostics), derivative_source, derivative_sensitivity_ok (NA for supplied derivatives or no samples), locations, derivatives (full diagnostics per sampled point), and note.

Examples

identity |> vc_arc_length(c(0,1),df=function(x)1)

Compute geometric area between two graphs

Description

Compute geometric area between two graphs

Usage

vc_area(
  f,
  interval,
  g = NULL,
  breaks = NULL,
  method = c("adaptive", "trapezoid", "simpson"),
  n = 32L,
  abs_tol = 1e-08,
  rel_tol = 1e-08,
  subdivisions = 100L
)

Arguments

f

Deterministic function accepting a real scalar and returning one finite real scalar. Vectorization is not required.

interval

Two finite real bounds, allowing reversed or equal bounds.

g

Second scalar boundary function; NULL means zero.

breaks

Optional finite strictly increasing interior integration split points, for example known intersections. These are not found automatically.

method

Quadrature rule: trapezoid, Simpson, or adaptive QUADPACK through stats::integrate(). Improper infinite bounds are not supported.

n

Initial number of equal cells for fixed rules; positive integer, even and at least two for Simpson. Ignored by the adaptive rule.

abs_tol, rel_tol

Nonnegative finite absolute and relative diagnostic tolerances; at least one must be positive. Adaptive integration also applies the tolerance restrictions of stats::integrate().

subdivisions

Positive integer maximum adaptive subinterval count; ignored by fixed rules.

Details

Integrates abs(f-g), not abs(integral(f-g)). Curve ordering may change. Bounds are sorted because area is unoriented; equal bounds give zero. Sampled values and totals must be finite. Known crossings can be supplied as breaks to help resolve the nonsmooth absolute difference. Finite sampling does not prove all crossings or features were resolved.

Value

Plain list with type, sorted interval, breaks, method, estimate (geometric area), signed_estimate (integral of f-g on increasing bounds), area and signed (complete segmented quadrature diagnostics), and note.

Examples

identity |> vc_area(c(-1,1),breaks=0)

Classify a possible critical point of a real function

Description

Evaluate stationarity, neighborhood signs and second-difference evidence. All classifications are conditional numerical evidence, never proofs.

Usage

vc_classify_critical(
  f,
  x0,
  radius = NULL,
  h = NULL,
  h2 = NULL,
  slope_tol = 1e-06,
  atol = 1e-08,
  rtol = 1e-04
)

Arguments

f

Deterministic function accepting a real scalar and returning one finite real scalar. Vectorization is not required.

x0

Finite real scalar evaluation point of the local model.

radius

Positive neighborhood radius. NULL uses 0.01*max(1,abs(x0)). Three radii (radius, radius/2, radius/4) are examined.

h

Positive finite real initial derivative step, or NULL for the heuristic used by vc_derivative(), evaluated with x = x0.

h2

Optional positive second-difference step, as in vc_taylor().

slope_tol

Nonnegative absolute tolerance for a stationary candidate.

atol

Nonnegative finite absolute tolerance for sensitivity comparisons.

rtol

Nonnegative finite relative tolerance for sensitivity comparisons.

Details

A finite central quotient is not sufficient for stationarity. Persistent disagreement of neighborhood one-sided slopes flags possible nonsmoothness. A shrinking gap can occur at a smooth stationary point even when vc_derivative's conservative side check fails. Stable near-zero central slopes plus reliable nonzero second differences support the second-derivative criterion under local smoothness. Otherwise consistent stable first-derivative signs at neighborhood points may support a first-sign criterion under continuity and side differentiability assumptions. Near-zero second derivative alone is inconclusive. Missing, noncontracting, conflicting or negligible neighborhood evidence is not classified automatically. The theoretical second-derivative test assumes differentiability near a stationary point and a nonzero second derivative there. The first-sign test requires signs on whole punctured neighborhoods, not merely samples. Three radii cannot prove these hypotheses, continuity or a local extremum. Warnings during derivative probes are suppressed; invalid probes become missing diagnostics, never stationary values.

Value

Plain list with type, x0, value, kind, classification, evidence, derivative, second_derivative, neighborhood, continuity_evidence and note. kind distinguishes stationary_candidate, nonsmooth_candidate, regular, flat_candidate and unresolved. classification is minimum, maximum, not_extremum, not_critical or inconclusive.

Examples

vc_classify_critical(function(x) x^2, 0)
vc_classify_critical(function(x) x^3, 0)$classification
abs |> vc_classify_critical(x0=0)

Assess a multivariable stationary candidate by the second derivative test

Description

Assess a multivariable stationary candidate by the second derivative test

Usage

vc_classify_stationary(
  f,
  point,
  assume_c2 = FALSE,
  h = NULL,
  hessian_h = NULL,
  tol_grad = 1e-05,
  tol_eigen = 1e-06,
  atol = 1e-08,
  rtol = 1e-04,
  warn = TRUE
)

Arguments

f

Deterministic scalar field accepting ONE numeric vector and returning one finite real scalar. For f(x,y), supply an explicit wrapper function(v)f(v[1],v[2]); no automatic signature guessing is performed.

point

Nonempty finite real coordinate vector. Optional names must be unique and nonempty and are passed to f.

assume_c2

Logical declaration by the caller that f is twice continuously differentiable in a neighborhood. Default FALSE prevents an extremum label; numerical stencils cannot verify this hypothesis.

h

NULL for per-coordinate vc_derivative heuristics, one positive finite step for all coordinates, or a positive finite vector of that dimension. No recycling of shorter vectors is allowed.

hessian_h

Positive scalar/vector second-difference step, or NULL for vc_hessian defaults. h controls first differences independently.

tol_grad

Positive absolute tolerance for the gradient norm and the finest left/right coordinate quotients. This is not an error bound.

tol_eigen

Positive absolute eigenvalue margin, enlarged by an empirical matrix refinement/roundoff allowance before classification.

atol

Nonnegative finite absolute tolerance for sensitivity comparisons.

rtol

Nonnegative finite relative tolerance for sensitivity comparisons.

warn

Logical scalar; warn when sensitivity diagnostics fail.

Details

Central coordinate quotients must be stable and small on BOTH finest sides. This additional stationarity check can pass at a smooth quadratic minimum when vc_gradient's stricter relative side-agreement flag fails; that original flag is retained, never rewritten. A cusp such as abs(x)+y^2 is not accepted just because central cancellation gives zero. Finite checks can still miss nonsmoothness or discontinuity.

With declared C2 regularity, a stationary candidate and reliable Hessian, positive/negative definite estimates suggest a strict minimum/maximum; eigenvalues of both signs suggest a saddle. Semidefinite, degenerate, unresolved or unavailable Hessians are inconclusive, never flat extrema. The margin is tol_eigen plus dimension times the maximum entry change over consecutive refinements plus dimension times the maximum finest roundoff indicator. It is a conservative diagnostic, NOT a certified perturbation bound. Near-stationary numerical points need not be exact critical points; all labels remain conditional. No boundary or constrained extremum test, higher-order test or global classification is performed.

Value

Plain list with type, point, value, classification, reason, stationary_evidence, gradient (unchanged complete engine result), side_max, hessian (complete result or NULL), eigenvalues, eigen_margin, matrix_allowance, assume_c2 and note. Labels are minimum, maximum, saddle, inconclusive or not_stationary; all are numerical assessments.

Examples

f <- function(v)v[1]^2+2*v[2]^2
f |> vc_classify_stationary(c(0,0),assume_c2=TRUE)

Sample concavity and search for smooth inflection candidates

Description

Sample concavity and search for smooth inflection candidates

Usage

vc_concavity(
  f,
  interval,
  n = 201L,
  h = NULL,
  h2 = NULL,
  x_tol = 1e-08,
  atol = 1e-08,
  rtol = 1e-04,
  max_iter = 100L
)

Arguments

f

Deterministic function accepting a real scalar and returning one finite real scalar. Vectorization is not required.

interval

Increasing pair of finite real search bounds.

n

Integer number of grid samples, at least 5.

h

Positive finite real initial derivative step, or NULL for the heuristic used by vc_derivative(), evaluated with x = x0.

h2

Optional positive second-difference step, as in vc_taylor().

x_tol

Positive root refinement tolerance; candidates within 10*x_tol are merged, keeping the smallest sampled derivative residual.

atol

Nonnegative finite absolute tolerance for sensitivity comparisons.

rtol

Nonnegative finite relative tolerance for sensitivity comparisons.

max_iter

Positive integer limit for bracketed root refinement. Bounded local minimization uses stats::optimize() with its own stopping rule.

Details

Reuses the direct three-point second-difference engine from Taylor, with three-scale sensitivity and roundoff diagnostics. Only reliable nonzero signs label concavity; region bounds cover sample spans, not proved continuous intervals. Inflection candidates require opposite consistent reliable curvature signs at three radii, contracting function-value neighborhood evidence and a stable numerical first derivative. A zero second difference alone is not an inflection. Singular and unresolved candidates remain separate. Continuous curvature sign changes with unresolved first-derivative evidence are reported in singular_candidates, not asserted to be smooth inflections. Default neighborhood curvature steps are capped at one percent of distance from the candidate to avoid straddling its possible singularity. This finite search is incomplete; it need not detect inflections with nonexistent or singular derivatives. Positive/negative f” on an interval gives the usual concavity criterion; this function labels only sampled evidence. Second-difference O(h^2) truncation presumes sufficient fourth-order local smoothness and spacing. Numerical evidence does not prove continuity or a change of concavity. Invalid/warning-producing numerical probes are recorded as unavailable when their values fail validation; probing warnings are suppressed.

Value

Plain list with type, interval, scan (x, value, second_derivative, reliable, classification), regions (sample spans), inflections (x, value, left_sign, right_sign, status), singular_candidates (same columns), rejected_candidates, complete=FALSE, status (sampled or no_evaluable_curvature), refinements (attempted root refinements with residual/status/messages), note. Scan labels are concave_up, concave_down, near_zero or unresolved.

Examples

vc_concavity(function(x) x^3, c(-1,1))$inflections
f <- function(x) x^4
(f |> vc_concavity(interval=c(-1,1)))$inflections

Search for critical-point candidates on a finite interval

Description

Search for critical-point candidates on a finite interval

Usage

vc_critical_points(
  f,
  interval,
  n = 201L,
  h = NULL,
  x_tol = 1e-08,
  slope_tol = 1e-06,
  max_iter = 100L
)

Arguments

f

Deterministic function accepting a real scalar and returning one finite real scalar. Vectorization is not required.

interval

Increasing pair of finite real search bounds.

n

Integer number of grid samples, at least 5.

h

Positive finite real initial derivative step, or NULL for the heuristic used by vc_derivative(), evaluated with x = x0.

x_tol

Positive root refinement tolerance; candidates within 10*x_tol are merged, keeping the smallest sampled derivative residual.

slope_tol

Nonnegative absolute tolerance for a stationary candidate.

max_iter

Positive integer limit for bracketed root refinement. Bounded local minimization uses stats::optimize() with its own stopping rule.

Details

Uses vc_derivative(), sign-change root refinement and bounded minimization of absolute derivative near grid minima. All refined residuals are checked again. Low-derivative sampled runs are reported as possible flat intervals, not proved plateaus; isolated refined roots inside them are retained. Continuous stationary sets are not enumerated as infinitely many critical points. Neighborhood classification shares vc_classify_critical(). Known invalid stencils split derivative evidence; sign-change refinement assumes continuity and can miss discontinuities, even-multiplicity roots, narrow features or nonsmooth points. Completeness is never guaranteed. Candidates without derivatives are not stationary.

Value

Plain list with type, interval, points, classifications (full lists), scan (x, value, derivative), flat_intervals, boundary_samples, complete (always FALSE), status and note. status distinguishes unavailable derivatives, found candidates and no detected candidates. refinements records method, bounds, location, residual, status and error message for every attempted refinement; acceptance here means residual acceptance, not a proof of criticality. points includes x, value, derivative, kind, classification and evidence. Boundaries are separate from interior points.

Examples

f <- function(x) x^3-3*x
(f |> vc_critical_points(interval=c(-2,2)))$points

Estimate the Cartesian curl of a spatial vector field

Description

Estimate the Cartesian curl of a spatial vector field

Usage

vc_curl(
  f,
  point,
  method = "central",
  h = NULL,
  atol = 1e-08,
  rtol = 1e-04,
  warn = TRUE
)

Arguments

f

Function of a Cartesian vector returning three finite real components.

point

Finite real Cartesian vector of length three.

method

One difference method, or one per coordinate. Explicit one-sided methods can be used at known coordinate-domain boundaries.

h

NULL for per-coordinate vc_derivative heuristics, one positive finite step for all coordinates, or a positive finite vector of that dimension. No recycling of shorter vectors is allowed.

atol

Nonnegative finite absolute tolerance for sensitivity comparisons.

rtol

Nonnegative finite relative tolerance for sensitivity comparisons.

warn

Logical scalar; warn when sensitivity diagnostics fail.

Details

Curl uses the right-handed Cartesian convention. Reliability summarizes the two partial derivatives used per component. To evaluate a time-dependent field at fixed time, capture that time in f.

Value

List with estimate, refinements, component reliability and full Jacobian.

Examples

vc_curl(function(p)c(-p[2],p[1],0),c(1,2,0))$estimate

Evaluate curvature and signed torsion of a spatial curve

Description

Evaluate curvature and signed torsion of a spatial curve

Usage

vc_curvature_torsion(
  curve,
  t,
  velocity = NULL,
  acceleration = NULL,
  jerk = NULL,
  h = NULL,
  h2 = NULL,
  h3 = NULL
)

Arguments

curve

Function of one scalar parameter returning a finite real three-vector in Cartesian x,y,z order.

t

One finite real parameter value.

velocity, acceleration

Optional functions giving the first and second derivatives in Cartesian order. Each supplied function must return a finite real three-vector. The caller supplies its mathematical validity.

jerk

Optional function giving the third derivative as a finite real Cartesian three-vector. Evaluated only when the frame is resolved.

h, h2

Optional positive initial central steps for velocity and acceleration, respectively. Defaults use the Jacobian and Hessian scales.

h3

Optional positive initial step for the direct third difference. The default is max(1, abs(t)) times machine epsilon to the power 1/5.

Details

Curvature is the norm of the velocity crossed with acceleration divided by speed cubed. Torsion is the signed scalar triple product of the three derivatives divided by the squared norm of that cross product. Torsion requires resolved nonzero curvature. A vanishing computed cross product at resolved speed gives zero estimated curvature. Numerically unresolved curvature and speed are labeled. A torsion estimate with a third-derivative indicator at least as large as the binormal projection is labeled unresolved_torsion. A finite, nonzero magnitude outside the representable range is reported as NA with status unrepresentable. Numerical jerk uses direct four-point stencils at three scales. Stencils may leave the curve domain. The indicators are heuristic and do not establish smoothness or provide certified error bounds.

Value

List with type curvature_torsion, frame, curvature, torsion, their separate statuses, the third derivative, its source and numerical diagnostics. Unavailable quantities are NA.

Examples

helix <- function(t)c(cos(t),sin(t),t/2)
measures <- vc_curvature_torsion(helix,0)
c(curvature=measures$curvature,torsion=measures$torsion)

Integrate speed along a spatial parametric curve

Description

Integrate speed along a spatial parametric curve

Usage

vc_curve_length(
  curve,
  interval,
  velocity = NULL,
  h = NULL,
  breaks = NULL,
  method = c("adaptive", "trapezoid", "simpson"),
  n = 32L,
  abs_tol = 1e-08,
  rel_tol = 1e-08,
  subdivisions = 100L
)

Arguments

curve

Function of one scalar parameter returning a finite real three-vector in Cartesian x,y,z order.

interval

Two finite parameter endpoints. Length uses their increasing order, regardless of traversal direction.

velocity

Optional function returning the Cartesian derivative as a finite real three-vector. The caller supplies its mathematical validity.

h

Optional positive finite numerical derivative step.

breaks

Optional finite strictly increasing interior integration split points, for example known intersections. These are not found automatically.

method

Quadrature rule: trapezoid, Simpson, or adaptive QUADPACK through stats::integrate(). Improper infinite bounds are not supported.

n

Number of initial subintervals for fixed quadrature, as in vc_integrate(). Adaptive quadrature ignores this count.

abs_tol, rel_tol

Nonnegative finite absolute and relative diagnostic tolerances; at least one must be positive. Adaptive integration also applies the tolerance restrictions of stats::integrate().

subdivisions

Positive integer maximum adaptive subinterval count; ignored by fixed rules.

Details

Length uses increasing parameter bounds and is nonnegative. A zero interval gives zero without evaluations. With no supplied velocity, central Jacobian stencils can leave the interval or cross a break. Supply velocity when the curve is undefined at needed stencil points. Split known nonsmooth pieces using breaks and prefer adaptive quadrature at corners. The speed formula requires a suitable piecewise smooth parameterization. Quadrature diagnostics cover the sampled speed and omit derivative error.

Value

List with type curve_length, sorted interval, estimate, integral diagnostics, speed samples, derivative source, numerical Jacobian results (in sample order) and a separate derivative sensitivity flag.

Examples

vc_curve_length(function(t)c(cos(t),sin(t),t),c(0,2*pi),
  velocity=function(t)c(-sin(t),cos(t),1))

Sample an oriented spatial parametric curve

Description

Sample an oriented spatial parametric curve

Usage

vc_curve_sample(curve, interval, n = 101L)

Arguments

curve

Function of one scalar parameter returning a finite real three-vector in Cartesian x,y,z order.

interval

Two finite parameter endpoints. Reversed endpoints reverse the sample order. Equal endpoints produce one sample.

n

Integer number of samples, at least two. Equal endpoints override this count and produce a single sample.

Details

Samples preserve the supplied parameter order. A plotted polyline approximates the sampled curve. Coincident spatial points are allowed.

Value

List with type curve3d, interval and samples (t,x,y,z).

Examples

vc_curve_sample(function(t)c(cos(t),sin(t),t),c(0,2*pi),n=20)

Integrate a Cartesian field over a cylindrical-coordinate solid

Description

Integrate a Cartesian field over a cylindrical-coordinate solid

Usage

vc_cylindrical_integrate(
  f,
  interval,
  radial_lower,
  radial_upper,
  height_lower,
  height_upper,
  method = c("simpson", "trapezoid"),
  n_outer = 8L,
  n_middle = 8L,
  n_inner = 8L,
  abs_tol = 1e-08,
  rel_tol = 1e-08
)

Arguments

f

Scalar field accepting one vector in physical x,y,z order.

interval

Angular bounds in radians, reversed/equal allowed; span at most 2*pi to avoid repeated angular coverage.

radial_lower, radial_upper

Nonnegative ordered radius functions of theta.

height_lower, height_upper

Functions of one vector in theta,r order, returning ordered finite vertical bounds.

method

Simpson or trapezoid fixed quadrature.

n_outer, n_middle, n_inner

Initial cell counts, each refined internally.

abs_tol, rel_tol

Nonnegative diagnostic tolerances, one positive.

Details

Uses x=rcos(theta), y=rsin(theta), z=z and Jacobian r, then reuses vc_triple_integrate unchanged. All nested diagnostics survive. Error indicators remain heuristic; caller justifies change-of-variables, integrability and bounds between samples. Negative sampled radii and spans exceeding one turn are rejected. Sampled fields must be finite, including at the axis; no automatic removable-singularity extension. Angular reversal changes sign. No spherical or adaptive nested rule.

Value

Full nested triple result with type cylindrical_integral; stored engine coordinates are theta,r,z, while f receives physical x,y,z.

Examples

(function(v)1) |> vc_cylindrical_integrate(c(0,2*pi),function(t)0,function(t)1,
  function(v)0,function(v)2,n_outer=2,n_middle=2,n_inner=2)

Sample a cylindrical surface generated by parallel straight rulings

Description

Sample a cylindrical surface generated by parallel straight rulings

Usage

vc_cylindrical_surface(
  curve,
  interval,
  s_range,
  direction,
  n_t = 31L,
  n_s = 11L
)

Arguments

curve

Function of one scalar parameter returning a finite real three-vector in Cartesian x,y,z order.

interval

Two finite parameter endpoints. Reversed endpoints reverse the sample order. Equal endpoints produce one sample.

s_range

Finite ruling distances in traversal order.

direction

Nonzero Cartesian vector, normalized before use.

n_t, n_s

Number of nodes along the generating curve and rulings.

Details

The surface is curve(t) + s times the unit direction. The generating curve may be noncircular. Negative s is allowed.

Value

Surface sample with u as curve parameter and v as ruling distance, plus the stored generating curve and unit ruling direction.

Examples

vc_cylindrical_surface(function(t)c(cos(t),sin(t),0),c(0,pi),
  c(-1,1),c(0,0,2),n_t=5,n_s=3)

Approximate a derivative with finite differences

Description

Evaluate finite difference quotients at three decreasing step sizes. These are numerical approximations, never a proof of differentiability.

Usage

vc_derivative(
  f,
  x,
  method = c("central", "forward", "backward"),
  h = NULL,
  atol = 1e-08,
  rtol = 1e-04,
  warn = TRUE
)

Arguments

f

Function accepting a real scalar and returning one finite real scalar. It should be deterministic. Vectorization is not required.

x

Finite real scalar at which to approximate the derivative.

method

One of "central", "forward", or "backward".

h

Positive finite real initial step. NULL uses max(1, abs(x)) times machine epsilon to the power 1/3 for central differences or 1/2 for one-sided differences. This heuristic is not optimal for every function or physical scale.

atol

Nonnegative finite absolute tolerance for sensitivity comparisons.

rtol

Nonnegative finite relative tolerance for sensitivity comparisons.

warn

Logical scalar; warn when sensitivity diagnostics fail.

Details

For positive s the forward quotient is (f(x+s)-f(x))/s, the backward quotient is (f(x)-f(x-s))/s, and the central quotient is (f(x+s)-f(x-s))/(2*s). The actual representable displacements are used as denominators to account for floating-point rounding of x+s and x-s. For sufficiently smooth functions these have nominal truncation orders one, one, and two, respectively, on an equally spaced stencil.

Steps h, h/2 and h/4 are evaluated. The last approximation is returned. Stability requires both successive changes to be at most atol + rtol * max(abs(the two estimates)). For central differences, the finest left and right quotients must also agree by this criterion. Failure produces a diagnostic and, by default, a warning. Reported changes are sensitivity measures, not rigorous error bounds.

Central differences require finite values on both sides, and one-sided methods require only their selected side and x. Out-of-domain values, collapsed or overflowing stencils, and nonfinite quotients are errors. One-sided results need not equal a two-sided derivative, especially at domain boundaries. Stable results can occur at discontinuities, cusps, or unresolved oscillations; even agreement of all checks is not proof. Cancellation, underflow, and large additive offsets can also conceal error.

Value

A plain list with estimate, x, method, h, a diagnostics data frame (step, forward, backward, estimate; unused sides are NA), changes (absolute successive changes), stable, side_agreement (NA for one-sided methods), reliable (the conjunction of applicable checks, not a mathematical guarantee), and a character note explaining that limitation.

Examples

vc_derivative(function(x) x^3, 2)$estimate
sin |> vc_derivative(x = 0, method = "central")
vc_derivative(abs, 0, warn = FALSE)$reliable
vc_derivative(sqrt, 1, method = "forward")$estimate

Compare a differential with a finite change

Description

Approximate dy = f'(x0) * dx and compare it with the actual sampled change delta_y = f(x0 + dx) - f(x0). The differential is a local linear approximation; it is generally different from the finite change.

Usage

vc_differential(
  f,
  x0,
  dx,
  method = c("central", "forward", "backward"),
  h = NULL,
  atol = 1e-08,
  rtol = 1e-04,
  warn = TRUE
)

Arguments

f

Deterministic function accepting a real scalar and returning one finite real scalar. Vectorization is not required.

x0

Finite real scalar evaluation point of the local model.

dx

Finite real scalar displacement. Zero and negative values are allowed. For nonzero dx, x0 + dx must be finite and distinct from x0.

method

One of "central", "forward", or "backward".

h

Positive finite real initial derivative step, or NULL for the heuristic used by vc_derivative(), evaluated with x = x0.

atol

Nonnegative finite absolute tolerance for sensitivity comparisons.

rtol

Nonnegative finite relative tolerance for sensitivity comparisons.

warn

Logical scalar; warn when sensitivity diagnostics fail.

Details

In exact mathematics, differentiability implies delta_y = f'(x0)*dx + o(abs(dx)) as dx tends to zero. Here the slope is numerical: remainder includes derivative approximation and rounding errors, and is not a rigorous Taylor error bound. The function must be finite at x0 + dx, as well as at the derivative stencil. One-sided derivative choices do not certify a two-sided differential.

Value

Plain list with type ("differential"), x0, y0, x1, y1, dx, dy, delta_y, remainder (delta_y - dy), tangent (full vc_tangent result), and note. dx is the requested displacement; actual_dx is the representable x1 - x0, also returned. The difference can matter at floating-point scale.

Examples

vc_differential(function(x) x^2, 1, dx = 0.1)
sin |> vc_differential(x0 = 0, dx = -0.1)

Approximate a directional derivative on its actual line restriction

Description

Approximate a directional derivative on its actual line restriction

Usage

vc_directional(
  f,
  point,
  direction,
  method = c("central", "forward", "backward"),
  h = NULL,
  atol = 1e-08,
  rtol = 1e-04,
  warn = TRUE,
  gradient = NULL
)

Arguments

f

Deterministic scalar field accepting ONE numeric vector and returning one finite real scalar. For f(x,y), supply an explicit wrapper function(v)f(v[1],v[2]); no automatic signature guessing is performed.

point

Nonempty finite real coordinate vector. Optional names must be unique and nonempty and are passed to f.

direction

Nonzero finite real vector matching point. It is normalized by scaled arithmetic to avoid squared-norm overflow/underflow. No change in direction magnitude changes the mathematical unit-direction derivative.

method

One of "central", "forward", or "backward".

h

Initial step in the line parameter, or NULL for max(1,abs(point)) times the one-variable epsilon heuristic. Every active coordinate must move representably at each nonzero stencil parameter; otherwise an error asks for rescaling or a larger step, rather than returning a false zero.

atol

Nonnegative finite absolute tolerance for sensitivity comparisons.

rtol

Nonnegative finite relative tolerance for sensitivity comparisons.

warn

Logical scalar; warn when sensitivity diagnostics fail.

gradient

Optional vc_gradient result at this same point/value for a diagnostic dot-product comparison. NULL does not compute any gradient.

Details

Differentiates t -> f(point+t*direction) at zero with vc_derivative(), rather than assuming the gradient formula. With a supplied gradient, agreement is checked against atol+rtol times the larger magnitude, and both diagnostic flags must pass for compatible/mismatch labels. The identity with the dot product requires appropriate differentiability; agreement of finitely many probes is not a proof. Discontinuous or nonsmooth fields can have misleading symmetric quotients. One-sided methods yield only one-sided evidence. Normalized components lost to underflow are errors. For mathematically axis-aligned directions, use exact zeros rather than roundoff-sized components from trigonometric evaluations at cardinal angles.

Value

Plain list with type, point, value, direction (unit vector), method, estimate, derivative (full one-variable diagnostics), reliable, optional gradient_dot and difference (NA without gradient), gradient_comparison (not_requested, compatible, mismatch or inconclusive), and note.

Examples

f <- function(v)v[1]^2+2*v[2]^2
g <- f |> vc_gradient(c(1,2))
f |> vc_directional(c(1,2),direction=c(3,4),gradient=g)

Estimate the divergence of a square vector field

Description

Estimate the divergence of a square vector field

Usage

vc_divergence(
  f,
  point,
  method = "central",
  h = NULL,
  atol = 1e-08,
  rtol = 1e-04,
  warn = TRUE
)

Arguments

f

Function of a Cartesian vector returning the same number of finite real components as the input.

point

Nonempty finite real coordinate vector. Optional names must be unique and nonempty and are passed to f.

method

One difference method, or one per coordinate. Explicit one-sided methods can be used at known coordinate-domain boundaries.

h

NULL for per-coordinate vc_derivative heuristics, one positive finite step for all coordinates, or a positive finite vector of that dimension. No recycling of shorter vectors is allowed.

atol

Nonnegative finite absolute tolerance for sensitivity comparisons.

rtol

Nonnegative finite relative tolerance for sensitivity comparisons.

warn

Logical scalar; warn when sensitivity diagnostics fail.

Details

The estimate is the trace of the Jacobian. Reliability summarizes only the diagonal entries. Numerical sensitivity does not certify differentiability or bound the divergence error.

Value

List with estimate, refinements, reliable and the full Jacobian.

Examples

vc_divergence(function(p)c(p[1],2*p[2]),c(1,2))$estimate

Integrate over a Cartesian region with nested fixed quadrature

Description

Integrate over a Cartesian region with nested fixed quadrature

Usage

vc_double_integrate(
  f,
  interval,
  lower,
  upper,
  order = c("yx", "xy"),
  method = c("simpson", "trapezoid"),
  n_outer = 16L,
  n_inner = 16L,
  abs_tol = 1e-08,
  rel_tol = 1e-08
)

Arguments

f

Scalar field taking one numeric vector in x,y order.

interval

Finite outer bounds, possibly reversed or equal.

lower, upper

Functions giving finite ordered inner bounds.

order

Inner then outer coordinate: yx (type I) or xy (type II).

method

Simpson or trapezoid rule.

n_outer, n_inner

Initial cell counts, refined at both levels.

abs_tol, rel_tol

Nonnegative diagnostic tolerances, one positive.

Details

Reuses vc_integrate unchanged. Adds its outer error indicator to the sum of absolute finest outer weights times inner error indicators. This is heuristic, never a certified bound. All inner flags are retained. Finite sampling does not prove integrability, Fubini hypotheses or boundary ordering between samples. Split known singularities and complex regions. Outer reversal changes sign; sampled inner reversal is rejected. Equal bounds contribute zero without field evaluations. Signed integrals are not geometric volumes. Polar and adaptive nested quadrature are not included.

Value

List with estimate, error_estimate, tolerance_met, full outer and cached inner vc_integrate results, sections, order, interval and status.

Examples

(function(v)v[1]+2*v[2]) |>
  vc_double_integrate(c(0,1),function(x)0,function(x)x)

Evaluate the Frenet frame of a spatial curve

Description

Evaluate the Frenet frame of a spatial curve

Usage

vc_frenet_frame(
  curve,
  t,
  velocity = NULL,
  acceleration = NULL,
  h = NULL,
  h2 = NULL
)

Arguments

curve

Function of one scalar parameter returning a finite real three-vector in Cartesian x,y,z order.

t

One finite real parameter value.

velocity, acceleration

Optional functions giving the first and second derivatives in Cartesian order. Each supplied function must return a finite real three-vector. The caller supplies its mathematical validity.

h, h2

Optional positive initial central steps for velocity and acceleration, respectively. Defaults use the Jacobian and Hessian scales.

Details

The frame follows increasing parameter t. It uses B in the direction of the cross product of velocity and acceleration and N in the direction of B crossed with T. Zero supplied velocity gives zero_speed. A zero or numerically unresolved normal component leaves only the tangent available (unresolved_curvature). Numerical velocity can give unresolved_speed. Resolution uses the last refinement change and a roundoff indicator for each numerical derivative, plus machine precision for the cross product. These indicators and the stored sensitivity diagnostics are heuristic. Central stencils may leave the curve's domain or cross a nonsmooth point. Supply derivatives at such points when the required derivatives exist. Use lapply() to evaluate the frame at several parameters.

Value

List with type frenet_frame, t, point, velocity, acceleration, unit tangent, principal normal, binormal, status, derivative sources and numerical diagnostics. Each unavailable direction is a three-vector of NA.

Examples

helix <- function(t)c(cos(t),sin(t),t/2)
vc_frenet_frame(helix,0,velocity=function(t)c(-sin(t),cos(t),.5),
  acceleration=function(t)c(-cos(t),-sin(t),0))

Explore the fundamental theorem of calculus numerically

Description

Explore the fundamental theorem of calculus numerically

Usage

vc_fundamental(
  f,
  x,
  lower = 0,
  method = c("adaptive", "trapezoid", "simpson"),
  n = 32L,
  abs_tol = 1e-08,
  rel_tol = 1e-08,
  subdivisions = 100L,
  h = NULL,
  derivative_method = c("central", "forward", "backward"),
  atol = 1e-08,
  rtol = 1e-04
)

Arguments

f

Deterministic function accepting a real scalar and returning one finite real scalar. Vectorization is not required.

x

Nonempty finite real vector of upper limits. Input order and duplicates are retained; limits below lower reverse orientation.

lower

Finite real scalar fixed lower integration limit.

method

Quadrature rule: trapezoid, Simpson, or adaptive QUADPACK through stats::integrate(). Improper infinite bounds are not supported.

n

Initial number of equal cells for fixed rules; positive integer, even and at least two for Simpson. Ignored by the adaptive rule.

abs_tol, rel_tol

Nonnegative finite absolute and relative diagnostic tolerances; at least one must be positive. Adaptive integration also applies the tolerance restrictions of stats::integrate().

subdivisions

Positive integer maximum adaptive subinterval count; ignored by fixed rules.

h

Positive finite initial difference step, or NULL for the vc_derivative() scale heuristic. Smaller is not always more accurate.

derivative_method

Central, forward or backward differences applied to the numerical accumulation function. One-sided comparisons are one-sided evidence only and can be used near domain boundaries.

atol, rtol

Nonnegative finite sensitivity/agreement tolerances. Agreement threshold is atol + rtol*abs(f(x)).

Details

Reuses vc_integrate() and vc_derivative(), not an analytical substitution of f(x) for A'(x). At each of the three difference scales, quadrature error estimates are multiplied by the absolute finite-difference coefficients and summed. This indicator accounts for amplification by small steps, but remains heuristic because its input errors are estimates. A consistent/mismatch status requires reliable derivative diagnostics, all sampled integrals meeting their diagnostic tolerances, and propagated indicators no larger than the agreement threshold at all three scales. Otherwise status is inconclusive, even if the computed values agree. Integration/derivative evaluation errors around a finite f(x) are retained as inconclusive messages. Nonfinite f(x) and invalid controls are errors. Integrability on the intervening interval and continuity at x are standard hypotheses for A'(x)=f(x) at an interior point. They are not established by this procedure. A point discontinuity can produce a numerical mismatch; a symmetric quotient alone does not prove a derivative at a jump.

Value

Plain list with type, lower, method, derivative_method, table (x, value, estimate, difference, agreement, derivative_reliable, integration_ok, quadrature_indicator, quadrature_resolved, status, message), results (derivative diagnostics, full sampled integrals and propagated quadrature diagnostics per point), and note. Unavailable estimates and differences are NA. Status is consistent, mismatch or inconclusive.

Examples

(function(x)x^2) |> vc_fundamental(x=c(0,1,2),lower=0)

Compare outward flux and volume divergence in Gauss' theorem

Description

Compare outward flux and volume divergence in Gauss' theorem

Usage

vc_gauss(
  field,
  x_range,
  y_range,
  z_range,
  divergence = NULL,
  h = NULL,
  method = c("simpson", "trapezoid"),
  n_outer = 4L,
  n_middle = 4L,
  n_inner = 4L,
  abs_tol = 1e-08,
  rel_tol = 1e-08
)

Arguments

field

Function of one Cartesian vector returning a finite three-component vector.

x_range, y_range, z_range

Finite strictly increasing endpoint pairs defining an axis-aligned box.

divergence

Optional function of position giving the scalar divergence. Defaults to vc_divergence().

h

Optional numerical divergence step or three coordinate steps.

method

Simpson or trapezoid fixed quadrature.

n_outer, n_middle, n_inner

Initial cell counts, each refined internally.

abs_tol, rel_tol

Nonnegative diagnostic tolerances, one positive.

Details

The six outward unit normals are exact signed coordinate axes. The same coordinate-specific cell counts are used on each face and in the volume, with x outermost, then y and z. The caller supplies a C1 field on a neighborhood of the box. Central stencils can leave the box. Numerical agreement does not establish theorem hypotheses and quadrature indicators do not include derivative error.

Value

List with total outward flux, volume divergence, signed difference (flux minus divergence integral), comparison tolerance, per-face flux and quadrature diagnostics, outward normals and derivative sensitivity.

Examples

vc_gauss(identity,c(0,1),c(0,1),c(0,1),n_outer=2,n_middle=2,n_inner=2)$outward_flux

Approximate the gradient of a scalar field

Description

Approximate the gradient of a scalar field

Usage

vc_gradient(
  f,
  point,
  method = "central",
  h = NULL,
  atol = 1e-08,
  rtol = 1e-04,
  warn = TRUE
)

Arguments

f

Deterministic scalar field accepting ONE numeric vector and returning one finite real scalar. For f(x,y), supply an explicit wrapper function(v)f(v[1],v[2]); no automatic signature guessing is performed.

point

Nonempty finite real coordinate vector. Optional names must be unique and nonempty and are passed to f.

method

One difference method, or one per coordinate. Explicit one-sided methods can be used at known coordinate-domain boundaries.

h

NULL for per-coordinate vc_derivative heuristics, one positive finite step for all coordinates, or a positive finite vector of that dimension. No recycling of shorter vectors is allowed.

atol

Nonnegative finite absolute tolerance for sensitivity comparisons.

rtol

Nonnegative finite relative tolerance for sensitivity comparisons.

warn

Logical scalar; warn when sensitivity diagnostics fail.

Details

Reuses vc_partial(), which reuses the accepted one-variable engine. A reliable flag means only that its finite coordinate checks passed. Even all existing coordinate partials do not imply total differentiability or justify computing every directional derivative by a dot product. The engine's conservative side checks may fail at smooth stationary points.

Value

Plain list with type, point, value, estimate (named vector), results (full partial results), table (coordinate, label, method, h, estimate, reliable), reliable (all coordinate checks), and note.

Examples

(function(v)v[1]^2+2*v[2]^2) |> vc_gradient(c(x=1,y=2))

Compare the two integrals in Green's circulation theorem

Description

Compare the two integrals in Green's circulation theorem

Usage

vc_green(
  field,
  lower,
  upper,
  interval,
  lower_derivative = NULL,
  upper_derivative = NULL,
  rotation = NULL,
  orientation = c("counterclockwise", "clockwise"),
  boundary_method = c("simpson", "trapezoid", "adaptive"),
  n_boundary = 16L,
  method = c("simpson", "trapezoid"),
  n_outer = 8L,
  n_inner = 8L,
  abs_tol = 1e-08,
  rel_tol = 1e-08
)

Arguments

field

Function of one Cartesian vector c(x,y) returning c(P,Q).

lower, upper

Scalar functions defining the lower and upper y graphs.

interval

Two finite, strictly increasing x endpoints.

lower_derivative, upper_derivative

Optional derivatives of the y graphs.

rotation

Optional scalar function of c(x,y) giving dQ/dx - dP/dy. Defaults to numerical partial derivatives from vc_jacobian().

orientation

Boundary traversal. Clockwise negates the boundary circulation and the oriented interior integral.

boundary_method

Rule for vc_line_integral().

n_boundary

Initial fixed-rule cell count per boundary edge.

method

Simpson or trapezoid rule.

n_outer, n_inner

Initial cell counts, refined at both levels.

abs_tol, rel_tol

Nonnegative diagnostic tolerances, one positive.

Details

The region is a single strip between two graphs. Counterclockwise traversal follows the lower graph to the right, the right edge upward, the upper graph to the left and the left edge downward. Collapsed vertical edges contribute zero. The caller supplies a suitable simple piecewise smooth boundary and a C1 field on a neighborhood of the region. Finite sampled boundary checks cannot establish those hypotheses. Central stencils may leave the domain. Numerical agreement and error indicators are diagnostic only. Regions with holes need decomposition.

Value

List with circulation, signed interior integral, signed difference (circulation minus interior), comparison tolerance, both quadrature results, a summed error indicator, and separate derivative diagnostics.

Examples

vc_green(function(p)c(-p[2],p[1]),function(x)0,function(x)1,c(0,1),
  lower_derivative=function(x)0,upper_derivative=function(x)0,
  rotation=function(p)2,n_boundary=4,n_outer=2,n_inner=2)$circulation

Approximate a scalar-field Hessian with direct differences

Description

Approximate a scalar-field Hessian with direct differences

Usage

vc_hessian(f, point, h = NULL, atol = 1e-08, rtol = 1e-04, warn = TRUE)

Arguments

f

Deterministic scalar field accepting ONE numeric vector and returning one finite real scalar. For f(x,y), supply an explicit wrapper function(v)f(v[1],v[2]); no automatic signature guessing is performed.

point

Nonempty finite real coordinate vector. Optional names must be unique and nonempty and are passed to f.

h

Initial positive step(s) for second differences. NULL uses pmax(1,abs(point)) times machine epsilon to the power one quarter. One step or one per coordinate is allowed. Central interior stencils are always required; no automatic boundary fallback is applied.

atol

Nonnegative finite absolute tolerance for sensitivity comparisons.

rtol

Nonnegative finite relative tolerance for sensitivity comparisons.

warn

Logical scalar; warn when sensitivity diagnostics fail.

Details

Diagonal entries reuse the accepted direct .vc_second_difference engine used by vc_taylor. Mixed entries use four rectangle corners, never numerical differentiation of approximate gradients. Actual rectangle widths are used. Initial, half and quarter steps are retained; mixed roundoff indicators are 16*epsilon*max(abs(corners))/(width_i*width_j). These and diagonal indicators are heuristics, not certified error bounds. Near-zero curvature or large offsets may give conservative failed flags. Upper-triangle estimates are mirrored by construction. Symmetry is not a test of equality/existence of ordered mixed partials or of C2 regularity. All finite checks can miss nonsmoothness or sampling aliasing. No eigenvalue classification or extremum claim is made: a Hessian alone does not locate a critical point. The rectangle formula recovers the Hessian primitive embedded in original critical_points_nd/critical_points_2d, independently of their search/classification code.

Value

Plain list with type, point, value, estimate (symmetric matrix), reliable (logical matrix), all_reliable, table (upper-triangle entries, steps, estimate, stable, resolved, reliable), results (full direct stencil diagnostics), refinements (three matrices), evaluation_count and note.

Examples

f <- function(v)v[1]^2+v[1]*v[2]+2*v[2]^2
f |> vc_hessian(c(1,1),h=.01)

Compare numerical quadrature rules

Description

Compare numerical quadrature rules

Usage

vc_integral_compare(
  f,
  interval,
  methods = c("trapezoid", "simpson", "adaptive"),
  n = 32L,
  abs_tol = 1e-08,
  rel_tol = 1e-08,
  subdivisions = 100L,
  reference = NULL
)

Arguments

f

Deterministic function accepting a real scalar and returning one finite real scalar. Vectorization is not required.

interval

Two finite real bounds, allowing reversed or equal bounds.

methods

Nonempty unique vector of quadrature method names.

n

Initial number of equal cells for fixed rules; positive integer, even and at least two for Simpson. Ignored by the adaptive rule.

abs_tol, rel_tol

Nonnegative finite absolute and relative diagnostic tolerances; at least one must be positive. Adaptive integration also applies the tolerance restrictions of stats::integrate().

subdivisions

Positive integer maximum adaptive subinterval count; ignored by fixed rules.

reference

Optional finite analytical/reference integral.

Value

Plain list with type, interval, results (complete integration objects), table (method, estimate, error_estimate, tolerance_met, status, error, abs_error), reference and note. Actual reference errors are NA when reference is absent. No best method is asserted.

Examples

vc_integral_compare(sin,c(0,pi),reference=2)$table

Approximate a signed definite integral

Description

Approximate a signed definite integral

Usage

vc_integrate(
  f,
  interval,
  method = c("trapezoid", "simpson", "adaptive"),
  n = 32L,
  abs_tol = 1e-08,
  rel_tol = 1e-08,
  subdivisions = 100L
)

Arguments

f

Deterministic function accepting a real scalar and returning one finite real scalar. Vectorization is not required.

interval

Two finite real bounds, allowing reversed or equal bounds.

method

Quadrature rule: trapezoid, Simpson, or adaptive QUADPACK through stats::integrate(). Improper infinite bounds are not supported.

n

Initial number of equal cells for fixed rules; positive integer, even and at least two for Simpson. Ignored by the adaptive rule.

abs_tol, rel_tol

Nonnegative finite absolute and relative diagnostic tolerances; at least one must be positive. Adaptive integration also applies the tolerance restrictions of stats::integrate().

subdivisions

Positive integer maximum adaptive subinterval count; ignored by fixed rules.

Details

Fixed rules evaluate n and 2*n cells and return the finer result. Richardson diagnostics use abs(fine-coarse)/3 for trapezoids and /15 for Simpson. They assume sufficiently smooth functions and an asymptotic error regime; aliasing or missed narrow features can make them misleading. tolerance_met is only a numerical diagnostic, never a certified bound. Adaptive status preserves QUADPACK failure messages without claiming convergence. Evaluation errors and nonfinite sampled values/results stop. Scalar-only functions are supported. Reversed bounds negate the integral; equal bounds return zero without evaluating f. Integrals are signed, not geometric areas. No method proves integrability or discovers every singularity; split known discontinuities/singularities explicitly.

Value

Plain list with type, interval, method, estimate, error_estimate, tolerance, tolerance_met, status, message, n (finest fixed cell count or NA), table (finest fixed nodes, values, signed weights/contributions), refinement (coarse/fine estimates), subdivisions and note. Adaptive internal nodes are unavailable and table/refinement are NULL.

Examples

(function(x)x^2) |> vc_integrate(c(0,2),method="simpson")
vc_integrate(sin,c(0,pi),method="adaptive")

Approximate the Jacobian of a vector-valued function

Description

Approximate the Jacobian of a vector-valued function

Usage

vc_jacobian(
  f,
  point,
  method = "central",
  h = NULL,
  atol = 1e-08,
  rtol = 1e-04,
  warn = TRUE
)

Arguments

f

Deterministic function accepting one finite coordinate vector and returning a nonempty finite real vector of fixed dimension and names. Optional output names must be unique and nonempty. A scalar output is allowed and produces a one-row Jacobian.

point

Nonempty finite real coordinate vector. Optional names must be unique and nonempty and are passed to f.

method

One difference method, or one per coordinate. Explicit one-sided methods can be used at known coordinate-domain boundaries.

h

NULL for per-coordinate vc_derivative heuristics, one positive finite step for all coordinates, or a positive finite vector of that dimension. No recycling of shorter vectors is allowed.

atol

Nonnegative finite absolute tolerance for sensitivity comparisons.

rtol

Nonnegative finite relative tolerance for sensitivity comparisons.

warn

Logical scalar; warn when sensitivity diagnostics fail.

Details

Reuses vc_derivative on each output/coordinate restriction, with shared cached vector evaluations. It does not guess f(x,y) signatures or silently recycle output dimensions. All three relative refinement levels are retained. Entry checks do not prove total differentiability, bound matrix error or establish a chain-rule hypothesis. One-sided differences are labeled and provide only their selected coordinate-side evidence.

Value

Plain list with type, point, value, estimate (outputs by inputs), reliable (logical matrix), all_reliable, table, results (per-entry full derivative diagnostics), refinements (three estimate matrices), evaluation_count and note. Matrix names follow output/point names, or default to f1,... and x1,... . Table rows identify output and input index, labels, method, initial step, estimate, stable and reliable.

Examples

f <- function(v)c(first=v[1]^2+v[2],second=v[2]*v[3])
f |> vc_jacobian(c(1,2,3))

Assess an equality-constrained candidate using Lagrange multipliers

Description

Assess an equality-constrained candidate using Lagrange multipliers

Usage

vc_lagrange(
  f,
  g,
  point,
  assume_c2 = FALSE,
  h = NULL,
  hessian_h = NULL,
  tol_feasible = 1e-08,
  tol_stationary = 1e-05,
  rank_tol = 1e-08,
  tol_eigen = 1e-06,
  atol = 1e-08,
  rtol = 1e-04,
  warn = TRUE
)

Arguments

f

Deterministic scalar field accepting ONE numeric vector and returning one finite real scalar. For f(x,y), supply an explicit wrapper function(v)f(v[1],v[2]); no automatic signature guessing is performed.

g

Equality constraints g=0, either a deterministic vector-valued function accepting one coordinate vector, or a nonempty list of scalar functions. Optional constraint names must be fixed, unique and nonempty.

point

Nonempty finite real coordinate vector. Optional names must be unique and nonempty and are passed to f.

assume_c2

Caller declaration that BOTH f and all constraints are C2 in a neighborhood. FALSE prevents extremum labels. Numerical evidence cannot establish regularity, exact feasibility or exact stationarity.

h

NULL for per-coordinate vc_derivative heuristics, one positive finite step for all coordinates, or a positive finite vector of that dimension. No recycling of shorter vectors is allowed.

hessian_h

Positive scalar/vector second-difference step, or NULL for vc_hessian defaults. h controls first differences independently.

tol_feasible

Positive absolute infinity-norm constraint tolerance.

tol_stationary

Positive absolute infinity-norm tolerance for the Lagrange residual and its finest forward/backward coordinate quotients.

rank_tol

Positive relative/absolute SVD rank threshold factor. Singular values must exceed rank_tol*max(1,largest singular value) plus an empirical Jacobian refinement allowance. Rank depends on scaling.

tol_eigen

Positive absolute eigenvalue margin, enlarged by an empirical matrix refinement/roundoff allowance before classification.

atol

Nonnegative finite absolute tolerance for sensitivity comparisons.

rtol

Nonnegative finite relative tolerance for sensitivity comparisons.

warn

Logical; warn when the assessment is inconclusive.

Details

Evaluates a supplied candidate; it does not search for candidates. Uses L=f-sum(lambda_i*g_i), so grad f=transpose(J)lambda. vc_gradient, vc_jacobian and direct vc_hessian engines are reused unchanged. The SVD of J solves for multipliers without forming the normal equations JJ^T. Stored raw sensitivity flags remain unchanged. First-order evidence uses stable central estimates and BOTH small finest coordinate-side Lagrange residuals; individual zero partials can fail stricter relative side flags even for smooth fields. This criterion is finite evidence, not proof.

A full-row-rank Jacobian identifies an estimated tangent basis Z. With feasible/stationary evidence, declared C2 and reliable Hessian stencils, eigenvalues of transpose(Z)H_LZ suggest strict constrained minimum or maximum (definite), or saddle (both signs). Semidefinite, singular-rank, unresolved and zero-dimensional tangent cases remain inconclusive. The original bordered matrix is retained for teaching, but its arbitrary leading-minor sign pattern is not used as a universal classifier.

Eigenvalue margin is tol_eigen plus dimension times the maximum entry refinement change of H_L and weighted roundoff indicators. Jacobian rank allowance uses sqrt(m*n) times its maximum consecutive refinement change. These are heuristic sensitivity diagnostics, not certified matrix or tangent-space error bounds. Individual Hessian flags are required (zero multiplier constraint Hessians do not affect H_L reliability). Scaling, offsets and near-zero curvature may require informed h/hessian_h choices. No inequalities, boundary/global optimization, singular-constraint theory, higher-order classification or existence/completeness proof is supplied.

Value

Plain list with type, point, value, constraints, classification, reason, feasible, stationary_evidence, regular, rank, rank_threshold, singular_values, lambda, stationarity_residual, side_max, gradient, jacobian, hessians (objective/constraints), lagrangian_hessian, bordered_hessian, tangent_basis, reduced_hessian, eigenvalues, eigen_margin, control and note. Unavailable quantities are NULL/NA and engine failures remain in the corresponding diagnostics. Labels are minimum, maximum, saddle, inconclusive, infeasible or not_stationary. Multipliers at deficient rank are minimum-norm diagnostics, not unique.

Examples

f <- function(v)sum(v^2)
g <- function(v)sum(v)-1
f |> vc_lagrange(g=g,point=c(.5,.5),assume_c2=TRUE,hessian_h=.01)

Probe a finite numerical limit from one or both sides

Description

Probe a finite numerical limit from one or both sides

Usage

vc_limit(
  f,
  x0,
  side = c("both", "left", "right"),
  h = NULL,
  steps = 20L,
  atol = 1e-06,
  rtol = 1e-04
)

Arguments

f

Deterministic function accepting a real scalar and returning one finite real scalar. Vectorization is not required.

x0

Finite real approach point. f(x0) is never evaluated.

side

One of both, left or right.

h

Positive initial distance. NULL uses 0.1*max(1,abs(x0)).

steps

Integer number of halving distances, between 4 and 1000.

atol, rtol

Nonnegative absolute/relative comparison tolerances.

Details

Each side's last three values must agree within atol+rtol*max(abs(a),abs(b)); both-side estimates must also agree. This finite Cauchy-like check is evidence only. Divergence, oscillations, floating-point cancellation and aliased sampling can evade finite tests. Unbounded or unresolved sequences are not replaced by a finite limit or an asserted infinity. Invalid values remain NA. Collapsed/underflowed or overflowing approach points are errors. Existence is never proved.

Value

Plain list with type, x0, side, samples (x, distance, value, side), left, right (side summaries with estimate and stable), estimate (NA unless applicable checks pass), status, and note. status is compatible_finite, side_disagreement, unresolved or unavailable.

Examples

f <- function(x) sin(x)/x
f |> vc_limit(x0=0)
vc_limit(function(x) abs(x)/x,0)$status

Integrate a scalar or vector field along a parametric curve

Description

Integrate a scalar or vector field along a parametric curve

Usage

vc_line_integral(
  f,
  curve,
  interval,
  type = c("scalar", "work"),
  velocity = NULL,
  h = NULL,
  breaks = NULL,
  method = c("adaptive", "trapezoid", "simpson"),
  n = 32L,
  abs_tol = 1e-08,
  rel_tol = 1e-08,
  subdivisions = 100L,
  time_dependent = FALSE
)

Arguments

f

Function of one Cartesian vector, or of position and parameter when time_dependent is TRUE. Returns one finite scalar or a vector matching the curve dimension, according to type.

curve

Function of one scalar parameter returning a finite real Cartesian vector of length two or three.

interval

Two finite parameter endpoints in traversal order.

type

Scalar line integral with respect to arc length, or vector work using the dot product with the curve derivative.

velocity

Optional derivative of curve with the same dimension.

h

Optional positive finite numerical derivative step.

breaks

Optional finite strictly increasing interior integration split points, for example known intersections. These are not found automatically.

method

Quadrature rule: trapezoid, Simpson, or adaptive QUADPACK through stats::integrate(). Improper infinite bounds are not supported.

n

Number of initial subintervals for fixed quadrature, as in vc_integrate(). Adaptive quadrature ignores this count.

abs_tol, rel_tol

Nonnegative finite absolute and relative diagnostic tolerances; at least one must be positive. Adaptive integration also applies the tolerance restrictions of stats::integrate().

subdivisions

Positive integer maximum adaptive subinterval count; ignored by fixed rules.

time_dependent

Pass the curve parameter explicitly as f(position,t).

Details

Scalar integrals are invariant under interval reversal, including for signed scalar fields. Work changes sign. Reversal traverses the same parameterized field values, including when time_dependent is TRUE. Equal endpoints give zero without evaluating either function. Central stencils can leave the domain or cross breaks. Supply velocity at known boundaries and split nonsmooth pieces with breaks when appropriate. Quadrature diagnostics cover the sampled integrand and omit derivative error.

Value

List with estimate, interval, dimension, orientation, quadrature diagnostics on increasing bounds, samples in traversal order, derivative source, and separate numerical Jacobian diagnostics in sample order.

Examples

vc_line_integral(function(p)c(-p[2],p[1]),
  function(t)c(cos(t),sin(t)),c(0,2*pi),type="work",
  velocity=function(t)c(-sin(t),cos(t)))$estimate

Construct a numerical total differential and affine local model

Description

Construct a numerical total differential and affine local model

Usage

vc_linearization(
  f,
  point,
  dx = NULL,
  scales = c(1, 0.5, 0.25),
  gradient = NULL,
  method = "central",
  h = NULL,
  atol = 1e-08,
  rtol = 1e-04,
  warn = TRUE
)

Arguments

f

Deterministic scalar field accepting ONE numeric vector and returning one finite real scalar. For f(x,y), supply an explicit wrapper function(v)f(v[1],v[2]); no automatic signature guessing is performed.

point

Nonempty finite real coordinate vector. Optional names must be unique and nonempty and are passed to f.

dx

Optional increment vector, or matrix with one increment per row. Coordinates are positional; when both point and increments are named, names must agree in order. NULL constructs evaluators without probes.

scales

Strictly decreasing positive finite probe multipliers; default compares each increment at full, half and quarter scale.

gradient

Optional vc_gradient result at the same point and field value. When supplied, its diagnostics are retained and method, h, atol, rtol and warn are ignored; the gradient is not recomputed.

method

One difference method, or one per coordinate. Explicit one-sided methods can be used at known coordinate-domain boundaries.

h

NULL for per-coordinate vc_derivative heuristics, one positive finite step for all coordinates, or a positive finite vector of that dimension. No recycling of shorter vectors is allowed.

atol

Nonnegative finite absolute tolerance for sensitivity comparisons.

rtol

Nonnegative finite relative tolerance for sensitivity comparisons.

warn

Logical scalar; warn when sensitivity diagnostics fail.

Details

Reuses vc_gradient without modifying the accepted derivative engine. The candidate differential is sum(gradient*dx); the model is f(point)+sum(gradient*(new_point-point)). It is the mathematical total differential/tangent model only under appropriate total differentiability. Coordinate sensitivity checks do not establish this hypothesis. Probes compare the model with actual finite changes at point+scaled_dx. Comparison differential uses the representable displacement; the requested functional value is also retained. Absolute remainder divided by actual displacement norm is reported, not promoted to a differentiability test. Even decreasing ratios on finitely many directions are not a proof. Gradient approximation error and roundoff can produce a residual floor. Zero increments have no normalized remainder. Domain errors, collapsed active coordinates, scaling underflow/overflow and nonfinite diagnostics remain explicit probe statuses; they do not become apparently valid zeros. Callable evaluators reject invalid dimensions/nonfinite results. Probing may evaluate outside the coordinate stencils, so it can fail even when gradient diagnostics pass. A supplied gradient is checked at the point, not proven to belong to the same field everywhere.

Value

Plain list with type, point, value, gradient (full result), gradient_reliable, differential (function of an increment), model (function of an absolute point), comparison (table or NULL), probes (requested/actual increments, endpoints), scales, normal, unit_normal, normal_status, plane_coefficients, coefficient_status and note. For the candidate graph hyperplane, normal is (-gradient,1); plane_coefficients appends the offset to that vector. An unrepresentable offset is NA and failed unit normalization returns NULL, with explicit geometry statuses; the centered model remains usable. Table columns are probe, scale, distance, requested_differential, differential, approximation, value, change, remainder, normalized_remainder, displacement_error, status and message. Unavailable diagnostics are NA.

Examples

f <- function(v)v[1]^2+2*v[2]^2
a <- f |> vc_linearization(c(1,1),dx=c(.1,.2))
a$differential(c(.1,.2))
a$model(c(1.1,1.2))
a$comparison

Newton-Raphson iteration with explicit termination diagnostics

Description

Newton-Raphson iteration with explicit termination diagnostics

Usage

vc_newton(
  f,
  x0,
  df = NULL,
  h = NULL,
  max_iter = 50L,
  f_tol = 1e-08,
  x_tol = 1e-08,
  derivative_tol = 1e-12,
  method = c("central", "forward", "backward")
)

Arguments

f

Deterministic function accepting a real scalar and returning one finite real scalar. Vectorization is not required.

x0

Finite real scalar evaluation point of the local model.

df

Optional function returning a finite real derivative scalar. NULL uses vc_derivative(), retaining its diagnostics.

h

Positive finite real initial derivative step, or NULL for the heuristic used by vc_derivative(), evaluated with x = x0.

max_iter

Nonnegative integer maximum number of accepted updates.

f_tol

Nonnegative absolute numerical residual tolerance.

x_tol

Nonnegative relative step tolerance, scaled by max(1,abs(x_next)).

derivative_tol

Nonnegative absolute safety threshold for slope size.

method

One of "central", "forward", or "backward".

Details

Uses x_next=x-f(x)/df(x), without damping or fallback. The initial residual is checked before evaluating the slope. Later acceptance as converged requires residual <=f_tol and a relative step <=x_tol, or an exactly zero computed residual. A small step with a large residual is stagnation. Repeated iterates within x_tol flag a cycle, not convergence. These finite numerical tests are not a proof of a mathematical root. Near a simple root, sufficient smoothness and a sufficiently close start give the usual local Newton theory; arbitrary starts and multiple roots have no such general guarantee. Finite-difference derivatives also do not promise the quadratic rate of exact-derivative Newton theory. Small slopes, scale, rounding, restricted domains and poor derivative estimates can prevent convergence. Numerical derivative diagnostics that fail terminate the iteration conservatively. A supplied df is checked for finite scalar output, not independently certified to be the derivative of f. Warnings during numerical derivative probes and trial evaluations are suppressed; invalid results are retained as failure diagnostics rather than treated as usable values.

Value

Plain list with type, x0, estimate (last accepted iterate), converged, status, iterations (n, x, fx, dfx, step, residual, derivative_status), derivative_diagnostics, rejected_trial (or NULL), control (input numerical settings), and note. status is converged, max_iter, derivative_too_small, derivative_unreliable, nonfinite_derivative, nonfinite_evaluation, nonfinite_step, stagnation or cycle_detected. Unaccepted trials never replace the last valid iterate.

Examples

f <- function(x) x^2-2
f |> vc_newton(x0=1)
vc_newton(function(x) x^2, 0)$status
vc_newton(function(x) x^3-2*x+2, 0)$status

Newton iteration for a square nonlinear system

Description

Newton iteration for a square nonlinear system

Usage

vc_newton_system(
  f,
  x0,
  jacobian = NULL,
  h = NULL,
  method = "central",
  max_iter = 50L,
  f_tol = 1e-08,
  x_tol = 1e-08,
  jacobian_tol = 1e-12,
  backtrack = TRUE,
  max_backtrack = 20L,
  atol = 1e-08,
  rtol = 1e-04
)

Arguments

f

Deterministic function accepting one coordinate vector and returning a finite real vector of the same length (at least two). Output dimension and optional unique/nonempty names must remain fixed. Wrap f(x,y) explicitly as function(v)f(v[1],v[2]); no signature guessing is performed.

x0

Finite initial coordinate vector of length at least two. Optional unique/nonempty names are passed to f and jacobian.

jacobian

Optional function accepting the same vector and returning a finite real square matrix in output-row/input-column order. Entries are checked, but not certified to be derivatives; matrix names never reorder entries. NULL reuses vc_jacobian with complete sensitivity diagnostics.

h

NULL or positive scalar/per-coordinate first-difference steps.

method

One difference method or one per coordinate: central, forward or backward. Used only for the numerical Jacobian.

max_iter

Nonnegative integer maximum accepted updates.

f_tol

Nonnegative absolute infinity-norm residual tolerance.

x_tol

Nonnegative relative step tolerance, using maximum coordinate change divided by max(1,max(abs(next_point))). A small step alone is not convergence.

jacobian_tol

Nonnegative minimum reciprocal one-norm condition estimate. Matrices at or below this threshold are rejected before solving.

backtrack

Logical; TRUE halves a Newton step until its finite residual satisfies residual_next <= (1-1e-4*damping)*residual_current, or residual_next <= f_tol. This safeguard does not guarantee convergence. FALSE accepts any finite trial, recovering undamped Newton iteration.

max_backtrack

Nonnegative integer maximum step halvings per update. The full step is always attempted first.

atol, rtol

Nonnegative absolute/relative sensitivity tolerances passed to vc_jacobian; failed numerical entry flags terminate conservatively.

Details

Solves J*s=-f by a linear solve, never by an explicit inverse. The initial residual is checked before asking for a Jacobian. Later numerical convergence requires residual <= f_tol and a small relative step, or an exactly zero computed residual. A small step with excessive residual is stagnation. Repeated accepted points within x_tol trigger a cycle diagnostic. Rejected trials never replace the last valid iterate.

This recovers original newton_raphson2d's square-system recurrence and iterate records, separates graphics, generalizes dimension and retains conditioning, stencil and domain failures. Exact-Newton local theory requires appropriate differentiability, a nonsingular true Jacobian and a sufficiently close initial point. Arbitrary starts, damping, numerical derivatives, multiple roots and singular systems have no promised global convergence or quadratic rate. Finite residual tests do not prove a root, regularity, uniqueness or that a supplied Jacobian is correct. Fixed tolerances are scale-dependent; rescale poorly conditioned systems.

Value

Plain list with type, x0, estimate (last accepted point), value, converged, status, points and values (rows aligned with iterations), iterations (n, residual, step_norm, relative_step, damping, jacobian_rcond), jacobian_diagnostics, trials (all accepted/rejected attempted steps with point, value, residual, error and damping), control and note. A zero-update or failed search retains the initial row. Status is converged, max_iter, jacobian_unavailable, jacobian_unreliable, jacobian_singular, linear_solve_failed, nonfinite_step, invalid_trial, line_search_failed, stagnation or cycle_detected. Input/initial-field errors raise errors; failures after initialization return diagnostics without erasing history.

Examples

f <- function(v)c(v[1]^2+v[2]^2-1,v[1]-v[2])
f |> vc_newton_system(c(.8,.2))
vc_newton_system(function(v)v,c(0,0))$status

Sample osculating circles of a spatial curve

Description

Sample osculating circles of a spatial curve

Usage

vc_osculating_circle(
  curve,
  t,
  velocity = NULL,
  acceleration = NULL,
  h = NULL,
  h2 = NULL,
  n = 72L
)

Arguments

curve

Function of one scalar parameter returning a finite real three-vector in Cartesian x,y,z order.

t

Nonempty finite real vector of parameter values in the desired order.

velocity, acceleration

Optional functions giving the first and second derivatives in Cartesian order. Each supplied function must return a finite real three-vector. The caller supplies its mathematical validity.

h, h2

Optional positive initial central steps for velocity and acceleration, respectively. Defaults use the Jacobian and Hessian scales.

n

Number of circle segments, at least three.

Details

A circle at a resolved point has radius 1/curvature and center point plus radius times the principal normal. The sampled ring starts and ends at the curve point and initially follows the tangent. A ring is unavailable for unresolved curvature or speed, or when its geometry cannot be represented. The frame diagnostics are retained. The construction needs only the first two derivatives.

Value

List with type osculating_circle, t and circles in parameter order. Each circle stores the frame, curvature, radius, center, status and a three-column ring matrix when the circle is available.

Examples

curve <- function(t)c(cos(t),sin(t),t/2)
vc_osculating_circle(curve,c(0,pi/2))$circles[[1]]$radius

Sample the osculating ribbon of a spatial curve

Description

Sample the osculating ribbon of a spatial curve

Usage

vc_osculating_ribbon(
  curve,
  interval,
  velocity = NULL,
  acceleration = NULL,
  h = NULL,
  h2 = NULL,
  n = 61L,
  n_u = 9L,
  u_max = 1
)

Arguments

curve

Function of one scalar parameter returning a finite real three-vector in Cartesian x,y,z order.

interval

Two finite parameter endpoints. Reversed endpoints reverse the sample order. Equal endpoints produce one sample.

velocity, acceleration

Optional functions giving the first and second derivatives in Cartesian order. Each supplied function must return a finite real three-vector. The caller supplies its mathematical validity.

h, h2

Optional positive initial central steps for velocity and acceleration, respectively. Defaults use the Jacobian and Hessian scales.

n

Integer number of samples, at least two. Equal endpoints override this count and produce a single sample.

n_u

Number of samples across each normal segment, at least two.

u_max

Positive fraction of the curvature radius at most one.

Details

At each available parameter the segment is the curve point plus u times the radius times the principal normal. At u=1 it reaches the center of curvature. The stored curve retains its samples at unavailable sections. A reversed interval reverses columns and an equal interval samples one section. Surface interpolation is a sampled visualization.

Value

List with type osculating_ribbon, stored curve, normal fractions u, sections and grid matrices x, y, z with rows in u and columns in parameter order. Unavailable sections are entire columns of NA.

Examples

curve <- function(t)c(cos(t),sin(t),t/2)
vc_osculating_ribbon(curve,c(0,pi),n=9)$sections[[1]]$center

Approximate a coordinate partial derivative

Description

Approximate a coordinate partial derivative

Usage

vc_partial(
  f,
  point,
  coordinate,
  method = c("central", "forward", "backward"),
  h = NULL,
  atol = 1e-08,
  rtol = 1e-04,
  warn = TRUE
)

Arguments

f

Deterministic scalar field accepting ONE numeric vector and returning one finite real scalar. For f(x,y), supply an explicit wrapper function(v)f(v[1],v[2]); no automatic signature guessing is performed.

point

Nonempty finite real coordinate vector. Optional names must be unique and nonempty and are passed to f.

coordinate

Integer coordinate index from one to length(point).

method

One of "central", "forward", or "backward".

h

Positive finite real initial step. NULL uses max(1, abs(x)) times machine epsilon to the power 1/3 for central differences or 1/2 for one-sided differences. This heuristic is not optimal for every function or physical scale.

atol

Nonnegative finite absolute tolerance for sensitivity comparisons.

rtol

Nonnegative finite relative tolerance for sensitivity comparisons.

warn

Logical scalar; warn when sensitivity diagnostics fail.

Details

Holds every other coordinate fixed and reuses vc_derivative(). Its actual-displacement and three-scale checks remain unchanged. Existence of partial derivatives is not proof of differentiability. Finite samples cannot establish the existence of the mathematical partial derivative.

Value

Plain list with type, point, coordinate, value, estimate, derivative (complete vc_derivative diagnostics), reliable and note.

Examples

(function(v)v[1]^2+2*v[2]^2) |> vc_partial(c(1,2),coordinate=2)

Construct a regular or custom partition

Description

Construct a regular or custom partition

Usage

vc_partition(interval = NULL, n = 10L, breaks = NULL)

Arguments

interval

Finite increasing pair of bounds. NULL when breaks supplied.

n

Positive integer number of regular cells; ignored with breaks.

breaks

Optional finite strictly increasing vector of partition points. When interval is supplied, endpoints must agree exactly.

Value

Plain list with type, interval, breaks, n, mesh and cells (left, right, width, midpoint). All cells have positive representable width.

Examples

vc_partition(c(0,2),n=4)
vc_partition(breaks=c(0,.2,1,2))

Construct a rectangular product partition

Description

Construct a rectangular product partition

Usage

vc_partition2d(
  xlim = NULL,
  ylim = NULL,
  nx = 8L,
  ny = 8L,
  xbreaks = NULL,
  ybreaks = NULL
)

Arguments

xlim, ylim

Finite increasing coordinate bounds; NULL with custom breaks.

nx, ny

Positive regular cell counts, ignored with corresponding breaks.

xbreaks, ybreaks

Optional finite strictly increasing coordinate breaks.

Details

Reuses vc_partition unchanged. Mesh is the maximum cell diameter.

Value

Plain list with two validated vc_partition results and cell table (ix,iy,x0,x1,y0,y1,dx,dy,xmid,ymid,area). x varies fastest.

Examples

vc_partition2d(c(0,1),c(0,2),nx=2,ny=3)

Explore accumulation and signed regions interactively

Description

Explore accumulation and signed regions interactively

Usage

vc_plot_accumulation(
  result,
  f,
  fundamental = NULL,
  n = 101L,
  colors = c(curve = "#24476b", positive = "#188367", negative = "#c44736", accumulation
    = "#8250a3", derivative = "#dd8800"),
  alpha = 0.35,
  line_width = 2,
  line_dash = c("solid", "dash", "dot", "dashdot"),
  animate = TRUE,
  frame_ms = 600,
  xlim = NULL,
  title = NULL,
  xlab = "x",
  ylab = "f(x)",
  alab = "A(x)"
)

Arguments

result

Result from vc_accumulation().

f

The same scalar function used for accumulation. The sampled function is drawn without recomputing any integrals.

fundamental

Optional vc_fundamental() result with exactly the same lower limit and x vector. Its derivative estimates are overlaid on f; hover and open markers retain inconclusive/mismatch diagnostics.

n

Integer number of curve/fill samples, at least two per frame.

colors

Named curve, positive, negative, accumulation and derivative Plotly/CSS colors. Positive/negative identify heights above/below zero, not the sign of a reversed integral.

alpha

Finite fill opacity from zero to one.

line_width

Positive finite curve width.

line_dash

One of solid, dash, dot or dashdot for sampled curves.

animate

Logical. Multiple stored upper limits get playback and a slider; FALSE draws the last stored limit. A single limit is static.

frame_ms

Positive finite animation duration in milliseconds.

xlim

Optional finite increasing display bounds covering lower and every stored x. NULL selects their range with padding for a single point.

title

Optional scalar title.

xlab, ylab, alab

Scalar labels for x, f(x) and A(x).

Details

Only stored integrals and comparisons are displayed. Function sampling and linear joins between accumulation nodes are illustrative, not new quadrature. Fill is not an unsigned-area computation; for x below lower the integral reverses sign even though heights remain unchanged. Invalid f samples are gaps. Theorems, continuity and integrability are not visually certified. Linear axes preserve signed-area interpretation.

Value

Two-panel Plotly widget: sampled f with zero-based positive/negative fills between lower and selected x, and sampled accumulation with a synchronized zero-to-A segment. Orientation, integral estimate, estimated error and status appear in hover. All stored accumulation nodes remain visible.

Examples

if(requireNamespace("plotly",quietly=TRUE)) {
  f <- function(x)x^2
  f |> vc_accumulation(seq(0,2,length.out=9)) |> vc_plot_accumulation(f=f)
}

Display geometric area between sampled graphs

Description

Display geometric area between sampled graphs

Usage

vc_plot_area(
  result,
  f,
  g = NULL,
  n = 401L,
  colors = c(f = "#24476b", g = "#c44736", region = "#188367"),
  alpha = 0.35,
  line_width = 2,
  line_dash = c("solid", "dash", "dot", "dashdot"),
  title = NULL,
  xlab = "x",
  ylab = "y",
  xlim = NULL,
  ylim = NULL
)

Arguments

result

Result from vc_area().

f, g

The same scalar boundary functions used in calculation; NULL g means zero. Functions are sampled, but quadrature is not recomputed.

n

Integer curve sample count, at least two. Known stored breaks are also sampled to show supplied crossings.

colors

Named f, g and region Plotly/CSS colors.

alpha

Finite fill opacity between zero and one.

line_width

Positive finite curve width.

line_dash

Curve line style: solid, dash, dot or dashdot.

title

Optional scalar title; default reports stored geometric and signed estimates and the area tolerance diagnostic.

xlab, ylab

Scalar axis labels.

xlim, ylim

Optional finite increasing display ranges; NULL uses data.

Details

Crossings between samples can be missed. Invalid samples are gaps; neither quadrature nor rendering proves all features were resolved. Axes are linear to retain geometric meaning. Match f/g to the stored analysis.

Value

Plotly widget shading the sampled lower/upper envelopes, with both original graphs. Fill is a geometric region, not a new area calculation.

Examples

if(requireNamespace("plotly",quietly=TRUE)) {
  identity |> vc_area(c(-1,1),breaks=0) |> vc_plot_area(f=identity)
}

Plot sampled concavity and smooth inflection candidates

Description

Plot sampled concavity and smooth inflection candidates

Usage

vc_plot_concavity(
  result,
  f,
  xlim = NULL,
  n = 401L,
  colors = c(curve = "#24476b", line = "#c44736", point = "#188367", diagnostic =
    "#8250a3"),
  title = NULL,
  xlab = "x",
  ylab = "f(x)"
)

Arguments

result

Result from vc_critical_points(), vc_concavity() or vc_newton(), matching the selected plot function.

f

The same deterministic scalar function used for the calculation. Function values at the stored anchor points must match the result.

xlim

Finite increasing plot bounds. NULL uses the stored search interval, or the accepted Newton iterates with padding.

n

Integer number of curve samples, at least 2. The curve is a sampled visualization, not an exact representation or a continuity test.

colors

Named vector with curve, line, point and diagnostic colors.

title

Optional scalar plot title. NULL uses a descriptive default.

xlab, ylab

Scalar axis labels.

Value

Interactive plotly widget with sampled curvature labels in hover and inflection candidate markers; no proof of inflection is implied.

Examples

if (requireNamespace("plotly",quietly=TRUE)) {
  f <- function(x) x^3
  f |> vc_concavity(c(-1,1)) |> vc_plot_concavity(f=f)
}

Plot critical-point candidates and derivative evidence

Description

Plot critical-point candidates and derivative evidence

Usage

vc_plot_critical_points(
  result,
  f,
  xlim = NULL,
  n = 401L,
  colors = c(curve = "#24476b", line = "#c44736", point = "#188367", diagnostic =
    "#8250a3"),
  title = NULL,
  xlab = "x",
  ylab = "f(x)"
)

Arguments

result

Result from vc_critical_points(), vc_concavity() or vc_newton(), matching the selected plot function.

f

The same deterministic scalar function used for the calculation. Function values at the stored anchor points must match the result.

xlim

Finite increasing plot bounds. NULL uses the stored search interval, or the accepted Newton iterates with padding.

n

Integer number of curve samples, at least 2. The curve is a sampled visualization, not an exact representation or a continuity test.

colors

Named vector with curve, line, point and diagnostic colors.

title

Optional scalar plot title. NULL uses a descriptive default.

xlab, ylab

Scalar axis labels.

Details

Markers are conditional numerical candidates, not proven extrema. Sampled curves may miss singularities; invalid samples are gaps. Existing scan values and classifications are used without silently recomputing them.

Value

Interactive plotly htmlwidget. Analysis plots have function and derivative-evidence panels; Newton adds actual iteration steps and a residual history panel. Calculations are not rerun.

Examples

if (requireNamespace("plotly",quietly=TRUE)) {
  f <- function(x) x^3-3*x
  f |> vc_critical_points(c(-2,2)) |> vc_plot_critical_points(f=f)
}

Display stored curvature and torsion on a sampled spatial curve

Description

Display stored curvature and torsion on a sampled spatial curve

Usage

vc_plot_curvature_torsion(result, measures, scale = 1, title = NULL)

Arguments

result

Result of vc_curve_sample().

measures

Result of vc_curvature_torsion() for the same curve.

scale

Positive length of each displayed unit direction, in the physical coordinate units of the curve.

title

Optional character title.

Value

Plotly widget with the stored frame and a caption for the scalar measures and their statuses.

Examples

if (requireNamespace("plotly",quietly=TRUE)) {
  helix <- function(t)c(cos(t),sin(t),t/2)
  vc_plot_curvature_torsion(vc_curve_sample(helix,c(0,2*pi)),
    vc_curvature_torsion(helix,pi/4),scale=.7)
}

Display stored spatial curve samples

Description

Display stored spatial curve samples

Usage

vc_plot_curve(
  result,
  mode = c("lines", "markers", "lines+markers"),
  line = list(color = "#24476b", width = 4),
  marker = list(),
  title = NULL
)

Arguments

result

Result of vc_curve_sample().

mode

Plotly mode for lines, markers or both.

line, marker

Plotly style lists.

title

Optional character title.

Value

A Plotly widget in physical Cartesian coordinates. Parameter values are available in hover text. A one-point curve uses a marker.

Examples

if(requireNamespace("plotly",quietly=TRUE)) {
  vc_curve_sample(function(t)c(t,t^2,t^3),c(0,1)) |> vc_plot_curve()
}

Display stored sections of a cylindrical integration region

Description

Display stored sections of a cylindrical integration region

Usage

vc_plot_cylindrical_integral(
  result,
  view = c("sections", "projection"),
  title = NULL
)

Arguments

result

Result of vc_cylindrical_integrate().

view

Vertical fibers in Cartesian space or polar base projection.

title

Optional character title.

Details

Fibers are not a watertight surface. The base envelope includes degenerate height sections and is not a certified projection of positive- volume support. Curved base boundaries are joined by sampled chords.

Value

Plotly widget based only on stored sections, without new quadrature or field/boundary evaluations.

Examples

if(requireNamespace("plotly",quietly=TRUE)) {
  r <- vc_cylindrical_integrate(function(v)1,c(0,pi),function(t)0,function(t)1,
    function(v)0,function(v)2,n_outer=2,n_middle=2,n_inner=2)
  vc_plot_cylindrical_integral(r)
}

Plot a differential and the actual finite change

Description

Show dx, the approximate differential dy, and the finite change delta_y. Dy and delta_y are shown at the same endpoint: use hover and legend controls to compare overlapping segments.

Usage

vc_plot_differential(
  result,
  f,
  xlim = NULL,
  n = 401L,
  colors = c(curve = "#24476b", line = "#c44736", point = "#222222", differential =
    "#188367", change = "#8250a3"),
  title = NULL,
  xlab = "x",
  ylab = "y"
)

Arguments

result

Plain result list from the corresponding calculation function.

f

The same deterministic scalar function used for the calculation. Function values at the stored anchor points must match the result.

xlim

Optional increasing pair of finite real plot limits, containing the anchor points. NULL derives limits around the anchors.

n

Integer number of curve samples, at least 2. The curve is a sampled visualization, not an exact representation or a continuity test.

colors

Named character vector with entries curve, line, point, differential, and change; values are Plotly/CSS colors.

title

Optional scalar plot title. NULL uses a descriptive default.

xlab, ylab

Scalar axis labels.

Details

All sampling limitations of vc_plot_secant() apply. The subtitle identifies derivative sensitivity status and the selected method. The differential endpoint uses y0 + dy at the representable x1; dx is the requested increment, which can differ slightly from x1 - x0 in doubles.

Value

An interactive plotly htmlwidget with the function, approximate tangent, anchors, and separate labeled increment segments.

Examples

if (requireNamespace("plotly", quietly = TRUE)) {
  f <- function(x) x^2
  vc_differential(f, 1, 0.2) |> vc_plot_differential(f = f)
}

Plot a directional line restriction on a sampled scalar surface

Description

Plot a directional line restriction on a sampled scalar surface

Usage

vc_plot_directional(
  result,
  f,
  xlim = NULL,
  ylim = NULL,
  t_range = c(-1, 1),
  n = 61L,
  colors = c(surface = "#24476b", curve = "#188367", tangent = "#c44736", point =
    "#222222"),
  alpha = 0.45,
  line_width = 3,
  title = NULL,
  scene = list(aspectmode = "data")
)

Arguments

result

Two-dimensional vc_directional() result.

f

Deterministic scalar field accepting ONE numeric vector and returning one finite real scalar. For f(x,y), supply an explicit wrapper function(v)f(v[1],v[2]); no automatic signature guessing is performed.

xlim, ylim

Optional finite increasing surface bounds covering the point. NULL uses point plus/minus two; t_range controls the separate curve.

t_range

Finite increasing line-parameter bounds containing zero.

n

Integer number of contour samples per coordinate, at least two.

colors

Named surface, curve, tangent and point Plotly/CSS colors.

alpha

Finite contour opacity between zero and one.

line_width

Positive finite vector line width.

title

Optional scalar title; default reports numerical sensitivity.

scene

Plotly scene list for the three-dimensional vector view.

Details

Recovers the directional curve/surface idea of legacy directional_derivative3d. Curve height is sampled f(point+t*u), whereas the tangent height uses only the stored derivative estimate. The direction is a unit domain vector, so the parameter is domain distance. Failed diagnostics and one-sided methods are explicitly labeled. Missing samples are gaps, not proof that no intervening singularity exists.

Value

Plotly 3D surface with the actual line-restriction curve, numerical tangent through the stored point, and stored base point.

Examples

if(requireNamespace("plotly",quietly=TRUE)) {
  f <- function(v)v[1]^2+2*v[2]^2
  f |> vc_directional(c(1,1),c(1,1)) |> vc_plot_directional(f=f)
}

Display stored Cartesian integration sections

Description

Display stored Cartesian integration sections

Usage

vc_plot_double_integral(result, title = NULL)

Arguments

result

Result of vc_double_integrate().

title

Optional character title.

Details

No function evaluations or quadrature occur here. Straight segments connect stored boundary samples, not an exact curved boundary. Physical x,y axes are preserved for either order. No signed height is represented.

Value

Plotly widget of sampled boundary polygon and stored sections.

Examples

if(requireNamespace("plotly",quietly=TRUE)) {
  r <- vc_double_integrate(function(v)sum(v),c(0,1),function(x)0,function(x)x)
  vc_plot_double_integral(r)
}

Display a stored Frenet frame on a sampled spatial curve

Description

Display a stored Frenet frame on a sampled spatial curve

Usage

vc_plot_frenet_frame(
  result,
  frame,
  scale = 1,
  components = c("tangent", "normal", "binormal"),
  title = NULL
)

Arguments

result

Result of vc_curve_sample().

frame

Result of vc_frenet_frame() for the same curve at a parameter within the sampled interval.

scale

Positive length of each displayed unit direction, in the physical coordinate units of the curve.

components

Character vector selecting tangent, normal and/or binormal.

title

Optional character title.

Value

Plotly widget with the sampled curve, frame anchor and available selected directions. No curve or derivative functions are evaluated.

Examples

if(requireNamespace("plotly",quietly=TRUE)) {
  helix <- function(t)c(cos(t),sin(t),t/2)
  vc_plot_frenet_frame(vc_curve_sample(helix,c(0,2*pi)),
    vc_frenet_frame(helix,pi/4),scale=.7)
}

Display the box and outward normals for a Gauss comparison

Description

Display the box and outward normals for a Gauss comparison

Usage

vc_plot_gauss(result, title = NULL)

Arguments

result

Result of vc_gauss().

title

Optional character title.

Value

Plotly widget with outward arrows, signed face flux in hover text and both stored integral estimates. The field is not reevaluated.

Examples

if (requireNamespace("plotly",quietly=TRUE)) {
  result <- vc_gauss(identity,c(0,1),c(0,1),c(0,1),divergence=function(p)3,
    n_outer=2,n_middle=2,n_inner=2)
  vc_plot_gauss(result)
}

Plot a gradient with optional stored directional playback

Description

Plot a gradient with optional stored directional playback

Usage

vc_plot_gradient(
  result,
  f,
  directions = NULL,
  xlim = NULL,
  ylim = NULL,
  n = 61L,
  vector_scale = 1,
  colors = c(field = "#24476b", gradient = "#c44736", direction = "#188367", point =
    "#222222"),
  alpha = 0.6,
  line_width = 3,
  animate = TRUE,
  frame_ms = 400,
  title = NULL,
  scene = list(aspectmode = "data")
)

Arguments

result

Result from vc_gradient(), in dimension two or three.

f

Deterministic scalar field accepting ONE numeric vector and returning one finite real scalar. For f(x,y), supply an explicit wrapper function(v)f(v[1],v[2]); no automatic signature guessing is performed.

directions

Optional list of vc_directional results at the same point. Playback uses those stored unit directions/estimates; none are computed.

xlim, ylim

Optional finite increasing contour bounds covering the point. NULL covers the displayed gradient endpoint and unit directions. Used only in dimension two.

n

Integer number of contour samples per coordinate, at least two.

vector_scale

Positive finite display multiplier on the gradient vector. Hover retains the unscaled estimate. Unit directions have unit display length.

colors

Named field, gradient, direction and point Plotly/CSS colors.

alpha

Finite contour opacity between zero and one.

line_width

Positive finite vector line width.

animate

Logical; multiple stored directions get playback and slider. FALSE shows the last direction; a single direction remains static.

frame_ms

Positive finite frame duration in milliseconds.

title

Optional scalar title; default reports numerical sensitivity.

scene

Plotly scene list for the three-dimensional vector view.

Details

Recovers the original gradient_scalar vector and gradient_direction2d directional playback representations. Vectors are drawn in the domain; endpoints/hover identify direction and magnitude. A zero numerical gradient is not assigned an arbitrary preferred direction. No maximum/minimum or differentiability assertion follows from the arrows. Invalid contour evaluations are gaps, and axis aspect ratios preserve data proportions.

Value

Plotly widget: sampled contours plus gradient in dimension two, or gradient/point in three-dimensional domain coordinates. In 3D the scalar field itself is not drawn as an asserted four-dimensional surface.

Examples

if(requireNamespace("plotly",quietly=TRUE)) {
  f <- function(v)v[1]^2+2*v[2]^2
  f |> vc_gradient(c(1,1)) |> vc_plot_gradient(f=f)
}

Display the stored region and oriented boundary for a Green comparison

Description

Display the stored region and oriented boundary for a Green comparison

Usage

vc_plot_green(result, region, title = NULL)

Arguments

result

Result of vc_green().

region

Result of vc_region() sampled from the same graphs and interval.

title

Optional character title.

Value

Plotly widget showing the region, sampled orientation arrows and both integral estimates. No field or boundary is reevaluated.

Examples

if (requireNamespace("plotly",quietly=TRUE)) {
  lo <- function(x)0
  hi <- function(x)1
  result <- vc_green(function(p)c(-p[2],p[1]),lo,hi,c(0,1),
    rotation=function(p)2,n_outer=2,n_inner=2)
  vc_plot_green(result,vc_region(lo,hi,c(0,1)))
}

Visualize signed numerical quadrature

Description

Visualize signed numerical quadrature

Usage

vc_plot_integral(
  result,
  f,
  n = 401L,
  colors = c(curve = "#24476b", approximation = "#188367", nodes = "#c44736"),
  alpha = 0.3,
  line_width = 2,
  title = NULL,
  xlab = "x",
  ylab = "f(x)",
  xscale = c("linear", "log"),
  yscale = c("linear", "log")
)

Arguments

result

Result of vc_integrate().

f

The same deterministic scalar function used for the calculation. Function values at the stored anchor points must match the result.

n

Integer number of curve samples, at least 2. The curve is a sampled visualization, not an exact representation or a continuity test.

colors

Named curve, approximation and nodes Plotly/CSS colors.

alpha

Finite fill opacity between zero and one.

line_width

Positive finite curve/approximation line width.

title

Optional scalar plot title. NULL uses a descriptive default.

xlab, ylab

Scalar axis labels.

xscale, yscale

Plotly axis scale: linear or log. Log scales may hide nonpositive data and cannot faithfully show signed areas across zero.

Details

Plotting never recomputes quadrature. Stored node values are checked against f. Simpson arcs interpolate each consecutive pair of cells. Fill represents a signed-integral region, not an unsigned area calculation. A reversed orientation changes the integral sign without changing f. Hover reports the stored estimate, diagnostic and orientation. Sampled curves/fills can miss features and do not establish integrability.

Value

Plotly widget. Fixed rules show finest stored nodes and piecewise linear/parabolic interpolation with fill to zero. Adaptive results show only a sampled function with fill to zero, not QUADPACK's internal mesh.

Examples

if(requireNamespace("plotly",quietly=TRUE)) {
  f <- function(x)x^2
  f |> vc_integrate(c(0,2),method="simpson",n=4) |> vc_plot_integral(f=f)
}

View equality constraints, objective contours and Lagrange gradients

Description

View equality constraints, objective contours and Lagrange gradients

Usage

vc_plot_lagrange(
  result,
  f,
  g,
  xlim = NULL,
  ylim = NULL,
  n = 81L,
  vector_scale = 0.3,
  show_gradients = TRUE,
  show_weighted = FALSE,
  colors = c(point = "#222222", gradient = "#c44736", weighted = "#dd8800"),
  constraint_colors = "#8250a3",
  colorscale = "Viridis",
  alpha = 0.6,
  line_width = 2,
  marker_size = 10,
  title = NULL,
  xlab = "x",
  ylab = "y"
)

Arguments

result

Two-dimensional vc_lagrange result, including inconclusive or infeasible assessments. This is a supplied-candidate view, not an optimizer.

f, g

Same objective and constraints used in calculation.

xlim, ylim

Optional finite increasing bounds; NULL uses point +/- 1.

n

Integer samples per coordinate, at least two. Stored contour matrices use y rows and x columns. Unavailable samples are gaps.

vector_scale

Positive common display multiplier for gradient vectors. Magnitudes are not normalized; hover retains the unscaled estimates.

show_gradients

Logical; show objective and each constraint gradient when the stored first-derivative data are available.

show_weighted

Logical; additionally show lambda_i times grad(g_i). Their SUM, not each individual vector, matches grad(f) at a regular stationary candidate. They share the candidate as their display origin.

colors

Named point, gradient and weighted colors.

constraint_colors

One color or one per constraint; the same color is used for its zero set and unweighted gradient.

colorscale

Plotly name/list for the objective contours.

alpha

Objective contour opacity between zero and one.

line_width

Positive line/arrow width.

marker_size

Positive candidate marker size.

title

Optional scalar title; default reports conditional classification, reason and numerical constraint-rank diagnostic.

xlab, ylab

Scalar coordinate-axis labels.

Details

Functions are checked against stored candidate values, then sampled for context. A grid may miss singular/tangential/narrow zero sets; absence of a rendered zero contour does not mean no feasible point exists. Finite arrow endpoints that overflow are omitted. Labels remain conditional on the mathematical hypotheses and numerical evidence in result; this plot does not certify regularity, stationarity or an extremum.

Value

Plotly contour widget with candidate marker, zero constraints and stored gradient vectors, plus arrow annotations. Calculation and derivative assessment are not rerun. Legend controls toggle traces; arrowhead annotations are static overlays controlled by show_gradients/show_weighted.

Examples

if(requireNamespace("plotly",quietly=TRUE)) {
  f <- function(v)sum(v^2)
  g <- function(v)sum(v)-1
  f |> vc_lagrange(g,c(.5,.5),assume_c2=TRUE,hessian_h=.01) |>
    vc_plot_lagrange(f=f,g=g)
}

Plot finite limit probes without evaluating the approach point

Description

Plot finite limit probes without evaluating the approach point

Usage

vc_plot_limit(
  result,
  f,
  xlim = NULL,
  n = 401L,
  colors = c(curve = "#24476b", left = "#188367", right = "#c44736", limit = "#8250a3"),
  title = NULL,
  xlab = "x",
  ylab = "f(x)"
)

Arguments

result

Result from vc_limit().

f

The same deterministic scalar function used for the calculation. Function values at the stored anchor points must match the result.

xlim

Optional increasing pair of finite real plot limits, containing the anchor points. NULL derives limits around the anchors.

n

Integer number of curve samples, at least 2. The curve is a sampled visualization, not an exact representation or a continuity test.

colors

Named vector with curve, left, right and limit colors.

title

Optional scalar plot title. NULL uses a descriptive default.

xlab, ylab

Scalar axis labels.

Details

The approach point is excluded from all function evaluations. The lower panel uses logarithmic distance with smaller distances to the right. No proof of limit existence or infinity is implied.

Value

Plotly widget with sampled function, side probes and a distance panel. A finite compatible estimate is an open marker, not f(x0).

Examples

if (requireNamespace("plotly",quietly=TRUE)) {
  f <- function(x) sin(x)/x
  f |> vc_limit(0) |> vc_plot_limit(f=f)
}

Display stored samples from a line integral

Description

Display stored samples from a line integral

Usage

vc_plot_line_integral(result, title = NULL)

Arguments

result

Result of vc_line_integral().

title

Optional character title.

Details

Samples come from quadrature. Adaptive quadrature may omit endpoints, and connecting samples approximates the curve. Equal bounds leave no samples to display. No functions are reevaluated.

Value

Plotly widget. For planar scalar integrals, shows the sampled curve and the signed curtain up to the field height. Other integrals show the sampled path with local integrand values in hover text.

Examples

if (requireNamespace("plotly",quietly=TRUE)) {
  r <- vc_line_integral(function(p)p[1],function(t)c(t,t^2),
    c(-1,1),method="simpson")
  vc_plot_line_integral(r)
}

Plot a candidate tangent plane, coordinate tangents and linearization error

Description

Plot a candidate tangent plane, coordinate tangents and linearization error

Usage

vc_plot_linearization(
  result,
  f,
  xlim = NULL,
  ylim = NULL,
  n = 61L,
  colors = c(surface = "#24476b", plane = "#188367", x_tangent = "#c44736", y_tangent =
    "#8250a3", normal = "#555555", increment = "#dd8800", point = "#222222"),
  alpha = 0.5,
  plane_alpha = 0.35,
  line_width = 3,
  t_len = 0.5,
  show_surface = TRUE,
  show_plane = TRUE,
  show_tangents = TRUE,
  show_sections = TRUE,
  show_normal = FALSE,
  normal_scale = 1,
  animate = TRUE,
  frame_ms = 500,
  title = NULL,
  scene = list(aspectmode = "data")
)

Arguments

result

Two-dimensional vc_linearization() result.

f

Deterministic scalar field accepting ONE numeric vector and returning one finite real scalar. For f(x,y), supply an explicit wrapper function(v)f(v[1],v[2]); no automatic signature guessing is performed.

xlim, ylim

Optional finite increasing bounds containing the point; NULL covers the point and successfully evaluated probe endpoints.

n

Integer number of surface/plane samples per coordinate, at least two.

colors

Named surface, plane, x_tangent, y_tangent, normal, increment and point Plotly/CSS colors.

alpha

Finite original-surface opacity between zero and one.

plane_alpha

Finite plane opacity between zero and one.

line_width

Positive finite vector line width.

t_len

Positive finite half-length of coordinate tangent segments.

show_surface, show_plane, show_tangents, show_sections, show_normal

Logical display switches. Sections are sampled true coordinate curves; tangents are linear candidates. Normal uses the stored unit vector (-fx,-fy,1).

normal_scale

Positive finite display length for the normal vector.

animate

Logical; multiple valid probe rows get playback/slider; FALSE displays the last valid row. One valid row is static.

frame_ms

Positive finite frame duration in milliseconds.

title

Optional scalar title; default labels a candidate affine plane and the separate coordinate-sensitivity flag. It never certifies a tangent.

scene

Plotly 3D scene list for camera, axes and aspect settings.

Details

Calculation is not rerun. Surface and affine values are sampled separately with rows corresponding to y and columns to x. Invalid samples are gaps. Probe rows with unavailable values remain in result diagnostics but are omitted from geometry and counted in the default title. Hover retains scale, differential, finite change, remainder and normalized remainder. The plane is a mathematical tangent only if appropriate total differentiability holds; finite probes and partial checks do not prove it.

Value

Plotly widget with sampled scalar surface, candidate affine plane, coordinate tangent models and optional normal. Each displayed probe joins its predicted and actual heights above the same actual domain endpoint.

Examples

if(requireNamespace("plotly",quietly=TRUE)) {
  f <- function(v)v[1]^2+2*v[2]^2
  f |> vc_linearization(c(1,1),dx=c(.1,.2)) |> vc_plot_linearization(f=f)
}

Inspect a numerical derivative matrix and its stored refinements

Description

Inspect a numerical derivative matrix and its stored refinements

Usage

vc_plot_matrix(
  result,
  colors = c(negative = "#24476b", zero = "#ffffff", positive = "#c44736", unresolved =
    "#dd8800"),
  alpha = 0.95,
  digits = 5L,
  show_values = TRUE,
  show_diagnostics = TRUE,
  slider = TRUE,
  title = NULL
)

Arguments

result

A vc_jacobian() or vc_hessian() result.

colors

Named negative, zero, positive and unresolved Plotly/CSS colors.

alpha

Finite heatmap opacity between zero and one.

digits

Integer significant digits in displayed cell labels, 1 to 15; hover retains a more precise estimate.

show_values

Logical; display rounded values as cell annotations.

show_diagnostics

Logical; mark entries whose full sensitivity checks failed. Flags refer to the three-scale diagnostic, not only the visible level.

slider

Logical; allow selection among the three stored refinement matrices. FALSE draws only the finest matrix.

title

Optional scalar title. Default identifies matrix type, the selected relative refinement level and the numerical-only interpretation.

Details

Jacobian rows are outputs and columns are input coordinates; Hessian rows/columns are input coordinates. The first row is at the top. No derivatives are recomputed. Relative levels mean initial steps, halves and quarters, not a common absolute step for differently scaled coordinates. Hessian symmetry is imposed by its rectangle stencil, not established as equality/existence of ordered mixed partials. No extremum classification or total differentiability certificate is inferred from colors or flags.

Value

Plotly matrix widget with correctly labeled rows and columns, numeric hover, optional values, unresolved-entry markers and refinement selector. Slider changes both the matrix and its value annotations.

Examples

if(requireNamespace("plotly",quietly=TRUE)) {
  f <- function(v)v[1]^2+v[1]*v[2]+2*v[2]^2
  f |> vc_hessian(c(1,1),h=.01) |> vc_plot_matrix()
}

Plot Newton iterations, tangents and numerical residuals

Description

Plot Newton iterations, tangents and numerical residuals

Usage

vc_plot_newton(
  result,
  f,
  xlim = NULL,
  n = 401L,
  animate = TRUE,
  frame_ms = 500,
  colors = c(curve = "#24476b", line = "#c44736", point = "#188367", diagnostic =
    "#8250a3"),
  title = NULL,
  xlab = "x",
  ylab = "f(x)"
)

Arguments

result

Result from vc_critical_points(), vc_concavity() or vc_newton(), matching the selected plot function.

f

The same deterministic scalar function used for the calculation. Function values at the stored anchor points must match the result.

xlim

Finite increasing plot bounds. NULL uses the stored search interval, or the accepted Newton iterates with padding.

n

Integer number of curve samples, at least 2. The curve is a sampled visualization, not an exact representation or a continuity test.

animate

Logical; animate computed tangent updates when at least two computed outgoing steps exist. Initial-root, single-step and failed-before-step results remain static; no next iterate is fabricated.

frame_ms

Positive finite frame duration in milliseconds.

colors

Named vector with curve, line, point and diagnostic colors.

title

Optional scalar plot title. NULL uses a descriptive default.

xlab, ylab

Scalar axis labels.

Details

Tangent segments join the current function point to its actual computed Newton x-intercept. Final points without a computed outgoing step have no tangent-update frame. Hover and title include residual/status; numerical convergence does not guarantee a mathematical root.

Value

Interactive plotly widget with iteration geometry and residual history. Play/pause and a frame slider are available for multiple steps.

Examples

if (requireNamespace("plotly",quietly=TRUE)) {
  f <- function(x) x^2-2
  f |> vc_newton(1) |> vc_plot_newton(f=f)
}

Animate two-dimensional Newton system iterates and zero contours

Description

Animate two-dimensional Newton system iterates and zero contours

Usage

vc_plot_newton_system(
  result,
  f,
  xlim = NULL,
  ylim = NULL,
  n = 81L,
  colors = c(first = "#188367", second = "#8250a3", path = "#24476b", current =
    "#c44736", rejected = "#dd8800"),
  line_width = 2,
  marker_size = 9,
  alpha = 0.45,
  show_rejected = FALSE,
  animate = TRUE,
  frame_ms = 600,
  title = NULL,
  xlab = "x",
  ylab = "y"
)

Arguments

result

Two-dimensional vc_newton_system result, including failed runs.

f

The same vector-valued function used in the calculation.

xlim, ylim

Optional finite increasing display bounds. NULL covers accepted iterates plus a margin; rejected trials do not expand the view.

n

Integer samples per coordinate axis, at least two. Zero contours are sampled independently; missed/tangential roots are possible.

colors

Named first, second, path, current and rejected colors.

line_width

Positive finite curve/path width.

marker_size

Positive finite iterate marker size.

alpha

Opacity of optional rejected-trial markers, between zero and one.

show_rejected

Logical; display finite rejected trial coordinates, labeled as rejected and not connected to the accepted iterate path.

animate

Logical; TRUE plays stored accepted iterates, FALSE shows the complete path. A run with zero updates has a static initial marker.

frame_ms

Positive animation frame duration in milliseconds.

title

Optional scalar title; default reports stored termination status.

xlab, ylab

Scalar coordinate-axis labels.

Details

Invalid samples are gaps. f is checked against stored system values at every accepted point. Contour intersections illustrate possible roots, not proofs of existence or uniqueness. Rejected-trial markers, when requested, are a static overlay of all rejections and do not imply they occurred at each playback time. Only 2D systems are drawn; the engine supports higher dimensions, whose Jacobians can use vc_plot_matrix.

Value

Plotly widget with two zero level sets and accepted Newton path. Each frame includes the current iterate, residual and accepted damping. Contour matrices have y rows and x columns. The terminal frame is included even after failure; no updates or Jacobians are recomputed for plotting.

Examples

if(requireNamespace("plotly",quietly=TRUE)) {
  f <- function(v)c(v[1]^2+v[2]^2-1,v[1]-v[2])
  f |> vc_newton_system(c(.8,.2)) |> vc_plot_newton_system(f=f)
}

Display stored osculating circles

Description

Display stored osculating circles

Usage

vc_plot_osculating_circle(
  result,
  curve_samples = NULL,
  fill = c("ring", "disk"),
  show_radius = FALSE,
  title = NULL
)

Arguments

result

Result of vc_osculating_circle().

curve_samples

Optional result of vc_curve_sample() for the same curve covering the circle parameters.

fill

Display either rings or triangulated disks.

show_radius

Logical flag to draw a segment from each center to its curve point.

title

Optional character title.

Value

Plotly widget with stored anchors and available circles.

Examples

if (requireNamespace("plotly",quietly=TRUE)) {
  curve <- function(t)c(cos(t),sin(t),t/2)
  vc_plot_osculating_circle(vc_osculating_circle(curve,pi/2),
    vc_curve_sample(curve,c(0,pi)),show_radius=TRUE)
}

Display a stored osculating ribbon

Description

Display a stored osculating ribbon

Usage

vc_plot_osculating_ribbon(
  result,
  opacity = 0.4,
  show_centers = TRUE,
  title = NULL
)

Arguments

result

Result of vc_osculating_ribbon().

opacity

Ribbon opacity between zero and one.

show_centers

Logical flag to display the sampled centers of curvature.

title

Optional character title.

Value

Plotly widget with the stored curve and available ribbon sections. Surface gaps remain open and isolated sections are shown as line segments.

Examples

if (requireNamespace("plotly",quietly=TRUE)) {
  curve <- function(t)c(cos(t),sin(t),t/2)
  vc_plot_osculating_ribbon(vc_osculating_ribbon(curve,c(0,pi),n=19))
}

Display a stored polar integration domain in Cartesian coordinates

Description

Display a stored polar integration domain in Cartesian coordinates

Usage

vc_plot_polar_integral(result, title = NULL)

Arguments

result

Result of vc_polar_integrate().

title

Optional character title.

Details

Only stored sections are transformed. Curved boundaries are joined by straight chords. No quadrature or field/boundary evaluation is repeated. A full annulus is outlined by outer and reversed inner boundaries joined along the angular seam. This sampled domain is not a signed volume plot.

Value

Plotly widget with sampled inner/outer boundary and radial sections.

Examples

if(requireNamespace("plotly",quietly=TRUE)) {
  r <- vc_polar_integrate(function(v)1,c(0,pi),function(t)1,function(t)2)
  vc_plot_polar_integral(r)
}

Display a stored planar region in 2D or as a horizontal plate

Description

Display a stored planar region in 2D or as a horizontal plate

Usage

vc_plot_region(
  result,
  view = c("2d", "3d"),
  plane_z = 0,
  show_grid = TRUE,
  title = NULL
)

Arguments

result

Result of vc_region().

view

Filled 2D region or sampled 3D plate.

plane_z

Finite display height for the 3D plate, not an integration value.

show_grid

Logical; show stored vertical sections in the 3D view.

title

Optional character title.

Details

In 2D reuses vc_plot_double_integral's sampled-domain renderer. In 3D the grid has u rows/x columns and every height equals plane_z. The plate has zero thickness; display height is not scalar-field height. Interpolation may miss crossings/oscillations between samples. Degenerate sections may collapse surface triangles. Human rendering review is separate.

Value

Plotly widget based only on stored region samples; no boundary reevaluation, integration or area calculation is performed.

Examples

if(requireNamespace("plotly",quietly=TRUE)) {
  r <- vc_region(function(x)x^2,sqrt,c(0,1),n=8,n_u=4)
  vc_plot_region(r,view="3d",plane_z=2)
}

Description

Display the gradient and a stored related-rates velocity

Usage

vc_plot_related_rates(
  result,
  g,
  xlim = NULL,
  ylim = NULL,
  n = 61L,
  vector_scale = 1,
  title = NULL
)

Arguments

result

Result of vc_related_rates() in two dimensions.

g

Same scalar constraint used for calculation.

xlim, ylim

Optional contour bounds covering the point and velocity tip.

n

Number of samples per contour coordinate, at least two.

vector_scale

Positive display multiplier for both vectors.

title

Optional character title.

Details

Reuses vc_plot_gradient without recalculating derivatives or rates. The velocity segment is a local first-order vector, not an integrated path.

Value

Plotly widget; unresolved velocities are omitted. Sampled contours show the scalar field, not a certified constraint curve or path.

Examples

if(requireNamespace("plotly",quietly=TRUE)) {
  g <- function(v)sum(v^2)-25
  r <- vc_related_rates(g,c(4,3),c(-1,NA),TRUE)
  vc_plot_related_rates(r,g,vector_scale=.2)
}

Display a solid of revolution and optional section playback

Description

Display a solid of revolution and optional section playback

Usage

vc_plot_revolution(
  result,
  f,
  g = NULL,
  n = 81L,
  nt = 61L,
  colors = c(outer = "#24476b", inner = "#188367", axis = "#333333", profile = "#c44736",
    section = "#dd8800"),
  alpha = 0.6,
  line_width = 3,
  title = NULL,
  show_axis = TRUE,
  show_profiles = TRUE,
  show_caps = TRUE,
  curve_thetas = 0,
  curve_opacity = 1,
  sections = NULL,
  animate = TRUE,
  frame_ms = 600,
  scene = list(aspectmode = "data", xaxis = list(title = "x"), yaxis = list(title = "y"),
    zaxis = list(title = "z"))
)

Arguments

result

Result from vc_revolution().

f, g

The same scalar boundary functions used in calculation; NULL g means zero. Functions are sampled, but quadrature is not recomputed.

n

Integer curve sample count, at least two. Known stored breaks are also sampled to show supplied crossings.

nt

Integer angular sample count, at least four, including both 0 and 2*pi to close circles.

colors

Named outer, inner, axis, profile and section Plotly/CSS colors.

alpha

Finite fill opacity between zero and one.

line_width

Positive finite curve width.

title

Optional scalar title; default reports the stored volume, method and quadrature tolerance diagnostic.

show_axis, show_profiles, show_caps

Logical switches for rotation axis, generating boundary profiles and end faces. Caps affect graphics only.

curve_thetas

Finite real vector of profile angles in radians.

curve_opacity

Finite profile opacity between zero and one.

sections

Optional finite vector of independent coordinates within interval for section rings/connectors. NULL draws none.

animate

Logical; multiple sections get playback and a slider; FALSE displays the last section, one section is static.

frame_ms

Positive finite frame duration in milliseconds.

scene

Plotly scene list for axis labels, aspect ratio, camera and display scales. Default uses geometric data proportions and linear axes.

Details

Coordinates reuse the same radii/height rules as the calculation. Sampled surfaces can miss features and are not a geometric proof. Curves are generating profiles; when a region straddles its axis, an interior profile need not lie on the outer boundary. Cap display does not compute cap area or change the reported volume/lateral area. Use the same f/g as the calculation; default g remains zero even for a shifted rotation axis.

Value

Plotly 3D widget with washer outer/inner surfaces or shell upper/lower boundaries, optional end faces, generating profiles and rotation axis. Sections are rings/connectors of the stored procedure, not new integrals.

Examples

if(requireNamespace("plotly",quietly=TRUE)) {
  identity |> vc_revolution(c(0,1)) |> vc_plot_revolution(f=identity,sections=c(0,.5,1))
}

Draw signed Riemann rectangles with optional refinement animation

Description

Draw signed Riemann rectangles with optional refinement animation

Usage

vc_plot_riemann(
  result,
  f,
  n = 401L,
  colors = c(curve = "#24476b", positive = "#188367", negative = "#c44736", edge =
    "#333333"),
  alpha = 0.45,
  line_width = 1,
  animate = TRUE,
  frame_ms = 700,
  title = NULL,
  xlab = "x",
  ylab = "f(x)"
)

Arguments

result

Result from vc_riemann() or vc_riemann_convergence().

f

The same deterministic scalar function used for the calculation. Function values at the stored anchor points must match the result.

n

Integer number of curve samples, at least 2. The curve is a sampled visualization, not an exact representation or a continuity test.

colors

Named curve, positive, negative and edge Plotly/CSS colors.

alpha

Finite fill opacity between zero and one.

line_width

Nonnegative finite rectangle edge width.

animate

Logical; animate multiple stored refinements. A single stored sum is static. No new sums are computed by this function.

frame_ms

Positive finite animation frame duration in milliseconds.

title

Optional scalar plot title. NULL uses a descriptive default.

xlab, ylab

Scalar axis labels.

Details

Rectangles extend from zero to f(sample), including below zero. This baseline is deliberately fixed to preserve the integral interpretation. Invalid curve samples are gaps. The curve is sampled, not an integrability proof. Hover shows n, rule, signed sum and rectangle contribution.

Value

Plotly widget with sampled curve and zero-based signed rectangles.

Examples

if(requireNamespace("plotly",quietly=TRUE)) {
  f <- function(x)x^2
  f |> vc_riemann_convergence(c(0,2),reference=8/3) |> vc_plot_riemann(f=f)
}

Draw stored signed Riemann prisms independently of calculation

Description

Draw stored signed Riemann prisms independently of calculation

Usage

vc_plot_riemann2d(result, title = NULL)

Arguments

result

Result of vc_riemann2d().

title

Optional character title.

Details

For restricted regions these are prisms of the zero-extension approximation on the box, not exact clipped boundary cells. Sampled extrema are labeled as such. A prism below zero contributes negatively.

Value

Plotly mesh widget. Every rectangular cell extends from zero to its stored signed height. No new field or boundary evaluation is made.

Examples

if(requireNamespace("plotly",quietly=TRUE)) {
  vc_riemann2d(function(v)v[1]-v[2],c(0,1),c(0,1),nx=2,ny=2) |>
    vc_plot_riemann2d()
}

Plot an interactive secant and its function

Description

Display sampled function values and a local line with Plotly. Computation is performed separately by vc_secant(), vc_tangent(), or vc_differential().

Usage

vc_plot_secant(
  result,
  f,
  xlim = NULL,
  n = 401L,
  colors = c(curve = "#24476b", line = "#c44736", point = "#222222", differential =
    "#188367", change = "#8250a3"),
  title = NULL,
  xlab = "x",
  ylab = "y"
)

Arguments

result

Plain result list from the corresponding calculation function.

f

The same deterministic scalar function used for the calculation. Function values at the stored anchor points must match the result.

xlim

Optional increasing pair of finite real plot limits, containing the anchor points. NULL derives limits around the anchors.

n

Integer number of curve samples, at least 2. The curve is a sampled visualization, not an exact representation or a continuity test.

colors

Named character vector with entries curve, line, point, differential, and change; values are Plotly/CSS colors.

title

Optional scalar plot title. NULL uses a descriptive default.

xlab, ylab

Scalar axis labels.

Details

Function samples that raise errors or produce nonfinite/nonreal scalar values are gaps; warnings during curve sampling are suppressed. The plot fails if no finite sample exists. Finite samples across an unresolved discontinuity can still be joined: users must choose a suitable domain and sampling resolution. The anchor points are checked strictly. Graphical limits and line evaluations must be finite.

Value

An interactive plotly htmlwidget. Zoom, pan, hover and legend controls are available. No derivative calculation is performed here.

Examples

if (requireNamespace("plotly", quietly = TRUE)) {
  f <- function(x) x^2
  vc_secant(f, 1, 2) |> vc_plot_secant(f = f)
}

Animate stored secants approaching a numerical tangent

Description

Animate stored secants approaching a numerical tangent

Usage

vc_plot_secant_convergence(
  result,
  f,
  xlim = NULL,
  n = 401L,
  colors = c(curve = "#24476b", line = "#c44736", point = "#222222", differential =
    "#188367", change = "#8250a3"),
  title = NULL,
  xlab = "x",
  ylab = "y",
  animate = TRUE,
  frame_ms = 400,
  line_width = 3
)

Arguments

result

Result from vc_secant_convergence().

f

The same deterministic scalar function used for the calculation. Function values at the stored anchor points must match the result.

xlim

Optional increasing pair of finite real plot limits, containing the anchor points. NULL derives limits around the anchors.

n

Integer number of curve samples, at least 2. The curve is a sampled visualization, not an exact representation or a continuity test.

colors

Named character vector with entries curve, line, point, differential, and change; values are Plotly/CSS colors.

title

Optional scalar plot title. NULL uses a descriptive default.

xlab, ylab

Scalar axis labels.

animate

Logical; multiple stored steps get playback/slider. FALSE displays the last step; one step is always static.

frame_ms

Positive finite frame duration in milliseconds. Transition is zero to avoid interpolating artificial intermediate secants.

line_width

Positive finite animated secant width.

Details

No secants or derivatives are recomputed. Stored endpoints are checked against f. In central mode the secant is the chord of both endpoints, correcting the legacy line-through-x0 display. The tangent remains an approximation, including at cusps or domain boundaries.

Value

Plotly widget with sampled function, numerical tangent and its diagnostic label, actual secant lines and actual endpoint pairs.

Examples

if(requireNamespace("plotly",quietly=TRUE)) {
  f <- function(x)x^2
  f |> vc_secant_convergence(1) |> vc_plot_secant_convergence(f=f)
}

Display stored Cartesian solid faces or wireframes

Description

Display stored Cartesian solid faces or wireframes

Usage

vc_plot_solid_cartesian(
  result,
  mode = c("faces", "wireframe", "both"),
  faces = names(result$faces),
  opacity = 0.4,
  wire_step = 2L,
  title = NULL
)

Arguments

result

Result of vc_solid_cartesian().

mode

Faces, wireframe or both.

faces

Nonempty unique character subset of stored face names.

opacity

Surface opacity between zero and one.

wire_step

Positive integer stride for wire lines, retaining endpoints.

title

Optional character title.

Details

Wire rows/columns use the stored parameter grids. Faces can be selected independently. Interpolation is a display approximation; normal orientation, manifold structure and exact closure are not certified.

Value

Plotly widget consuming stored face data only. No boundary evaluation, integral calculation or automatic internal slices are performed.

Examples

if(requireNamespace("plotly",quietly=TRUE)) {
  s <- vc_solid_cartesian(function(x)0,function(x)1,function(v)0,
    function(v)1,c(0,1),n=2,n_u=2,n_v=2)
  vc_plot_solid_cartesian(s,mode="both")
}

Display stored cylindrical-solid patches or wireframes

Description

Display stored cylindrical-solid patches or wireframes

Usage

vc_plot_solid_cylindrical(
  result,
  mode = c("faces", "wireframe", "both"),
  faces = names(result$faces),
  opacity = 0.4,
  wire_step = 2L,
  title = NULL
)

Arguments

result

Result of vc_solid_cylindrical().

mode

Faces, wireframe or both.

faces

Nonempty unique selection of stored physical face names. Angular cut patches remain selectable even for a full turn.

opacity

Surface opacity between zero and one.

wire_step

Positive integer stride for wire lines, retaining endpoints.

title

Optional character title.

Details

For a periodic full cylinder one can omit theta_min/theta_max and a degenerate radial_inner axis patch. A periodic annulus normally uses radial_inner, radial_outer, z_lower and z_upper. Caller chooses patches; this is not automatic boundary-union or normal-orientation analysis.

Value

Plotly widget using unchanged face/wire renderer and stored Cartesian coordinates only. No geometry sampling, derivative or integral evaluation.

Examples

if(requireNamespace("plotly",quietly=TRUE)) {
  s <- vc_solid_cylindrical(function(t)1,function(t)2,function(v)0,function(v)1,
    c(0,2*pi),n=12,n_u=2,n_v=2)
  vc_plot_solid_cylindrical(s,faces=c("radial_inner","radial_outer","z_lower","z_upper"))
}

Display stored spherical shells and optional angular cuts

Description

Display stored spherical shells and optional angular cuts

Usage

vc_plot_solid_spherical(
  result,
  mode = c("faces", "wireframe", "both"),
  faces = c("radial_inner", "radial_outer"),
  opacity = 0.4,
  wire_step = 2L,
  title = NULL
)

Arguments

result

Result of vc_solid_spherical().

mode

Faces, wireframe or both.

faces

Named selection; default inner and outer radial shells. Use all stored names explicitly to include angular cut patches.

opacity

Surface opacity between zero and one.

wire_step

Positive integer stride for wire lines, retaining endpoints.

title

Optional character title.

Details

For a full shell, angular cuts are normally omitted and pole patches collapse. A ball's inner radius-zero shell collapses to the origin; select radial_outer alone if desired. For a restricted sector, select appropriate angular cuts explicitly. No automatic exterior-boundary union is computed.

Value

Plotly widget using unchanged Cartesian face/wire rendering, without boundary reevaluation or integration.

Examples

if(requireNamespace("plotly",quietly=TRUE)) {
  s <- vc_solid_spherical(function(t)0,function(t)pi,function(v)1,function(v)2,
    c(0,2*pi),n=12,n_u=8,n_v=2)
  vc_plot_solid_spherical(s,mode="both")
}

Display stored radial fibers of a spherical integration region

Description

Display stored radial fibers of a spherical integration region

Usage

vc_plot_spherical_integral(result, title = NULL)

Arguments

result

Result of vc_spherical_integrate().

title

Optional character title.

Details

No field/boundary reevaluation or quadrature. Radial fibers are not a watertight surface or a complete boundary mesh. Shell fibers start at the inner radius and preserve the empty core. Degenerate poles may overlap.

Value

Plotly widget of stored radial segments in physical x,y,z coordinates.

Examples

if(requireNamespace("plotly",quietly=TRUE)) {
  r <- vc_spherical_integrate(function(v)1,c(0,pi/2),function(t)0,function(t)pi/2,
    function(v)1,function(v)2,n_outer=2,n_middle=2,n_inner=2)
  vc_plot_spherical_integral(r)
}

Inspect two-dimensional stationary candidates and search evaluations

Description

Inspect two-dimensional stationary candidates and search evaluations

Usage

vc_plot_stationary(
  result,
  f,
  xlim = NULL,
  ylim = NULL,
  n = 61L,
  run = 1L,
  show_history = TRUE,
  animate = TRUE,
  max_frames = 40L,
  frame_ms = 300,
  colors = c(minimum = "#188367", maximum = "#c44736", saddle = "#8250a3", inconclusive =
    "#dd8800", history = "#24476b"),
  colorscale = "Viridis",
  alpha = 0.6,
  marker_size = 10,
  line_width = 2,
  title = NULL,
  xlab = "x",
  ylab = "y"
)

Arguments

result

Result of vc_stationary_points with two input coordinates.

f

Same scalar field used in the search, accepting one vector.

xlim, ylim

Finite increasing display bounds; NULL uses the search window, or the range of starts/candidates enlarged by one coordinate unit.

n

Integer samples per axis, at least two. Matrix rows represent y and columns x. Nonfinite or unavailable field samples remain gaps.

run

Integer run index whose objective evaluation history is shown.

show_history, animate

Logical switches. Playback shows stored objective evaluations, not optimizer iterations or a Newton/descent path.

max_frames

Positive integer maximum displayed history samples. Deterministic thinning keeps first/last samples; full history stays in result.

frame_ms

Positive playback duration in milliseconds.

colors

Named minimum, maximum, saddle, inconclusive and history colors.

colorscale

Plotly colorscale name or list for the sampled contours.

alpha

Opacity between zero and one for search-evaluation markers.

marker_size

Positive candidate marker size.

line_width

Positive history-line width.

title

Optional scalar title.

xlab, ylab

Scalar axis labels.

Details

No derivative or optimization is recomputed. Only f is sampled for context and checked against stored candidate values. Search evaluations may move uphill and include optimizer probes; their connecting polyline is not a mathematical flow. Failed residual evaluations are omitted from geometry but remain in the calculation history. All candidate labels are conditional numerical evidence; this plot does not establish regularity or completeness.

Value

Plotly contour widget with conditional candidate labels and optional evaluation playback. Hover retains residuals, stopping codes and statuses.

Examples

if(requireNamespace("plotly",quietly=TRUE)) {
  f <- function(v)v[1]^2+2*v[2]^2
  r <- vc_stationary_points(f,c(.1,.2),assume_c2=TRUE)
  r |> vc_plot_stationary(f=f)
}

Inspect stored stationary candidates on a sampled 3D graph

Description

Inspect stored stationary candidates on a sampled 3D graph

Usage

vc_plot_stationary_surface(
  result,
  f,
  xlim = NULL,
  ylim = NULL,
  n = 41L,
  colors = c(minimum = "#188367", maximum = "#c44736", saddle = "#8250a3", inconclusive =
    "#dd8800"),
  opacity = 0.65,
  marker_size = 6,
  title = NULL
)

Arguments

result

Two-coordinate result of vc_stationary_points().

f

Same scalar field, accepting one coordinate vector.

xlim, ylim

Finite increasing display bounds; default search bounds or starts/candidate extent enlarged by one unit.

n

Integer samples per coordinate, at least two. Matrix rows are y, columns x. Unavailable/nonfinite surface values are gaps.

colors

Named minimum,maximum,saddle,inconclusive Plotly colors.

opacity

Surface opacity between zero and one.

marker_size

Positive candidate marker size.

title

Optional character title.

Details

No optimization, derivative, Hessian or classification is repeated. Only f is sampled for the graph and checked at stored candidates. Surface interpolation is not exact geometry or a smoothness/completeness proof. Labels remain conditional on the calculation hypotheses and diagnostics; inconclusive candidates stay inconclusive. No optimizer history is shown as a path. Use vc_plot_stationary for objective-evaluation playback.

Value

Plotly surface and stored candidate markers with stored heights, conditional classification, residual and reason in hover text.

Examples

if(requireNamespace("plotly",quietly=TRUE)) {
  f <- function(v)v[1]^2+2*v[2]^2
  r <- vc_stationary_points(f,c(.1,.2),assume_c2=TRUE,warn=FALSE)
  vc_plot_stationary_surface(r,f)
}

Display stored Stokes circulation and curl flux

Description

Display stored Stokes circulation and curl flux

Usage

vc_plot_stokes(result, patch, title = NULL)

Arguments

result

Result of vc_stokes().

patch

Result of vc_surface_sample() for the same surface and ranges.

title

Optional character title.

Value

Plotly widget with the patch, oriented boundary and both estimates. No field or surface is reevaluated.

Examples

if (requireNamespace("plotly",quietly=TRUE)) {
  patch <- function(p)c(p[1],p[2],p[1]+p[2])
  result <- vc_stokes(function(p)c(-p[2],p[1],0),patch,c(0,1),c(0,1),
    n_boundary=4,n_outer=2,n_inner=2)
  vc_plot_stokes(result,vc_surface_sample(patch,c(0,1),c(0,1)))
}

Display a stored surface patch

Description

Display a stored surface patch

Usage

vc_plot_surface(result, opacity = 0.6, show_curve = TRUE, title = NULL)

Arguments

result

Result of vc_surface_sample() or vc_cylindrical_surface().

opacity

Surface opacity from zero to one.

show_curve

Show the stored generating curve when available.

title

Optional character title.

Value

Plotly widget displaying the stored geometry. A single row or column is drawn as a line, and a single node as a point.

Examples

if (requireNamespace("plotly",quietly=TRUE)) {
  vc_surface_sample(function(p)c(p[1],p[2],prod(p)),c(0,1),c(0,1)) |>
    vc_plot_surface()
}

Plot an approximate tangent and its function

Description

Display the approximation and its sensitivity status. A plotted line does not certify that the mathematical tangent exists.

Usage

vc_plot_tangent(
  result,
  f,
  xlim = NULL,
  n = 401L,
  colors = c(curve = "#24476b", line = "#c44736", point = "#222222", differential =
    "#188367", change = "#8250a3"),
  title = NULL,
  xlab = "x",
  ylab = "y"
)

Arguments

result

Plain result list from the corresponding calculation function.

f

The same deterministic scalar function used for the calculation. Function values at the stored anchor points must match the result.

xlim

Optional increasing pair of finite real plot limits, containing the anchor points. NULL derives limits around the anchors.

n

Integer number of curve samples, at least 2. The curve is a sampled visualization, not an exact representation or a continuity test.

colors

Named character vector with entries curve, line, point, differential, and change; values are Plotly/CSS colors.

title

Optional scalar plot title. NULL uses a descriptive default.

xlab, ylab

Scalar axis labels.

Details

All sampling limitations of vc_plot_secant() apply. The legend identifies an approximate tangent and the subtitle reports numerical sensitivity status. One-sided methods are identified explicitly.

Value

An interactive plotly htmlwidget with function, line and anchor.

Examples

if (requireNamespace("plotly", quietly = TRUE)) {
  vc_tangent(sin, 0) |> vc_plot_tangent(f = sin)
}

Compare a function and its numerical Taylor polynomial interactively

Description

Show the sampled function and polynomial above a signed/absolute error panel. Hover reports distance from the expansion point; zoom, pan and the horizontal range slider explore behavior away from that point.

Usage

vc_plot_taylor(
  result,
  f,
  xlim = NULL,
  n = 401L,
  colors = c(curve = "#24476b", polynomial = "#c44736", error = "#188367", point =
    "#222222"),
  title = NULL,
  xlab = "x",
  ylab = "y"
)

Arguments

result

Plain result from vc_taylor().

f

The same deterministic scalar function used for the calculation. Function values at the stored anchor points must match the result.

xlim

Optional increasing finite pair containing the expansion point. NULL uses the range of result$comparison$x together with x0, padded by ten percent; without a nonzero comparison range it uses x0 +/- 1.

n

Integer number of curve samples, at least 2. The curve is a sampled visualization, not an exact representation or a continuity test.

colors

Named character vector with curve, polynomial, error and point entries specifying Plotly/CSS colors.

title

Optional scalar plot title. NULL uses a descriptive default.

xlab, ylab

Scalar axis labels.

Details

Error means the sampled difference f(x)-P(x), not a rigorous Taylor remainder bound. Undefined/erroring/nonfinite function samples create gaps and NA errors. Warnings during sampling are suppressed. Polynomial overflow also creates gaps; at least one polynomial sample must be finite. A grid can miss singularities or oscillations. The subtitle displays diagnostic status and the number of evaluable errors.

Value

A plotly htmlwidget with function, polynomial, expansion point, signed error and absolute error traces. Derivatives are not recalculated.

Examples

if (requireNamespace("plotly", quietly = TRUE)) {
  exp |> vc_taylor(x0 = 0, x = seq(-1,1,length.out=21)) |>
    vc_plot_taylor(f = exp)
}

Display stored sections of a Cartesian triple-integration region

Description

Display stored sections of a Cartesian triple-integration region

Usage

vc_plot_triple_integral(
  result,
  view = c("sections", "projection"),
  title = NULL
)

Arguments

result

Result of vc_triple_integrate().

view

Stored 3D inner-coordinate sections or outer-middle projection.

title

Optional character title.

Details

Sections are stored fibers, not a watertight surface or quadrature cells. The projection joins sampled middle boundaries linearly, including degenerate fibers; it is a base-domain envelope, not a certified projection of the positive-volume support. Axis labels preserve physical coordinates.

Value

Plotly widget without new field/boundary evaluations or quadrature.

Examples

if(requireNamespace("plotly",quietly=TRUE)) {
  r <- vc_triple_integrate(sum,c(0,1),function(x)0,function(x)1,
    function(v)0,function(v)1,n_outer=2,n_middle=2,n_inner=2)
  vc_plot_triple_integral(r)
}

Display stored field arrows and an optional trajectory

Description

Display stored field arrows and an optional trajectory

Usage

vc_plot_vector_field(result, streamline = NULL, scale = NULL, title = NULL)

Arguments

result

Result of vc_vector_field_sample().

streamline

Optional vc_streamline() result.

scale

Positive maximum arrow length in Cartesian units. By default uses eight percent of the largest sampled axis span.

title

Optional plot title.

Value

Plotly widget using stored positions and vectors. Arrow lengths are proportional to magnitude and zero vectors are shown as points.

Examples

if (requireNamespace("plotly",quietly=TRUE)) {
  f <- function(p)c(-p[2],p[1],0)
  s <- vc_vector_field_sample(f,function(x)-1,function(x)1,
    function(p)0,function(p)0,c(-1,1),n=4,n_u=4,n_v=1)
  vc_plot_vector_field(s,vc_streamline(f,c(1,0,0),c(0,pi)))
}

Integrate a Cartesian scalar field over a polar region

Description

Integrate a Cartesian scalar field over a polar region

Usage

vc_polar_integrate(
  f,
  interval,
  lower,
  upper,
  method = c("simpson", "trapezoid"),
  n_outer = 16L,
  n_inner = 16L,
  abs_tol = 1e-08,
  rel_tol = 1e-08
)

Arguments

f

Scalar field taking one numeric vector in x,y order.

interval

Angular bounds in radians, reversed or equal allowed; absolute span at most 2*pi to prevent repeated angular coverage.

lower, upper

Radius functions of angle, nonnegative and ordered at sampled sections.

method

Simpson or trapezoid rule.

n_outer, n_inner

Initial cell counts, refined at both levels.

abs_tol, rel_tol

Nonnegative diagnostic tolerances, one positive.

Details

Applies x=rcos(theta), y=rsin(theta) and the Jacobian r, then reuses vc_double_integrate unchanged. f always receives Cartesian x,y. Requires finite field samples, including the origin when sampled; no automatic removable-singularity extension. Negative radii and spans above one revolution are rejected. Caller justifies boundary behavior between samples and change-of-variables/integrability hypotheses. Angular reversal changes the signed result. Error indicators are heuristic, not bounds.

Value

Full nested result with type polar_integral, parameter sections (outer is theta, lower/upper are radii), and nested engine diagnostics.

Examples

(function(v)1) |> vc_polar_integrate(c(0,2*pi),function(t)0,function(t)1)

Sample a planar region independently of integration

Description

Sample a planar region independently of integration

Usage

vc_region(lower, upper, interval = NULL, n = 40L, n_u = 20L, partition = NULL)

Arguments

lower, upper

Scalar boundary functions of x, ordered at sampled nodes.

interval

Finite increasing x bounds, or NULL with partition supplied.

n

Positive number of regular x strips, ignored with partition.

n_u

Positive number of subdivisions across each vertical section.

partition

Optional vc_partition result; reconstructed from breaks.

Details

Reuses vc_partition unchanged. Validates sampled ordering without swapping boundaries. Linear interpolation between sampled boundary values is a representation, not proof of topology, ordering between samples or exact curved boundaries. A single interval between two graphs is supported; disconnected vertical cross sections require justified decomposition. Equal boundary heights are allowed as degenerate sections. Every stored coordinate must be finite; fine representable grids are not guaranteed.

Value

Plain list with type region, partition, sections (outer,lower,upper), u blending fractions, grid (x,y matrices with u rows and x columns), strips (the scalar partition cell table) and note. No volume/area computed.

Examples

vc_region(function(x)x^2,sqrt,c(0,1),n=10,n_u=4)

Description

Assess and solve a missing rate on an implicit level constraint

Usage

vc_related_rates(
  g,
  point,
  rates,
  assume_differentiable = FALSE,
  h = NULL,
  tol_feasible = 1e-08,
  tol_rate = 1e-08,
  denom_tol = 1e-08,
  atol = 1e-08,
  rtol = 1e-04,
  warn = TRUE
)

Arguments

g

Scalar constraint accepting one coordinate vector; level g=0.

point

Finite coordinate vector, optionally named.

rates

Numeric vector of the same length, in coordinate order. NA marks unknown rates (an all-NA logical vector is also accepted); all supplied rates must be finite. If both vectors are named, names must match exactly in order.

assume_differentiable

Caller declaration of total differentiability near the point. Finite coordinate diagnostics cannot establish it.

h

NULL for per-coordinate vc_derivative heuristics, one positive finite step for all coordinates, or a positive finite vector of that dimension. No recycling of shorter vectors is allowed.

tol_feasible

Positive absolute tolerance for g(point).

tol_rate

Positive absolute tolerance for the first-order rate residual.

denom_tol

Positive denominator threshold factor, multiplied by max(1,max(abs(gradient))) and enlarged by empirical derivative changes.

atol

Nonnegative finite absolute tolerance for sensitivity comparisons.

rtol

Nonnegative finite relative tolerance for sensitivity comparisons.

warn

Logical scalar; warn when sensitivity diagnostics fail.

Details

Uses grad(g) dot rates=0 conditionally on a differentiable path lying on g=0 and the caller's total-differentiability hypothesis. Solves one missing component only after feasibility, derivative reliability and denominator gates pass. Changes between derivative levels and finest side disagreement form heuristic denominator/error indicators, not bounds. Multiple missing rates remain underdetermined; a numerically zero missing coefficient may give first_order_inconsistent or underdetermined evidence, never a trajectory existence/nonexistence proof. Small nonzero coefficients remain denominator_unresolved, not zero by assertion. Fully supplied rates can be assessed without division. No hidden signature/name remapping. Explicit time dependence can be modeled by including time as a coordinate and supplying its rate as one. No higher-order or path integration solver.

Value

Plain list with status, point, value, feasible, supplied_rates, rates (unknowns filled only when solved), estimate, candidate, unknown, gradient (full unchanged engine), denominator, denominator_margin, known_contribution, residual, rate_indicator, conditional and note.

Examples

g <- function(v)sum(v^2)-25
g |> vc_related_rates(c(x=4,y=3),c(-1,NA),assume_differentiable=TRUE)

Compute a volume of revolution from a planar strip region

Description

Compute a volume of revolution from a planar strip region

Usage

vc_revolution(
  f,
  interval,
  g = NULL,
  variable = c("x", "y"),
  axis = c("horizontal", "vertical"),
  axis_at = 0,
  breaks = NULL,
  quadrature = c("adaptive", "trapezoid", "simpson"),
  n = 32L,
  abs_tol = 1e-08,
  rel_tol = 1e-08,
  subdivisions = 100L
)

Arguments

f

Deterministic function accepting a real scalar and returning one finite real scalar. Vectorization is not required.

interval

Two finite real bounds, allowing reversed or equal bounds.

g

Second scalar boundary function; NULL means zero.

variable

Independent coordinate of f and g: x means y=f(x), y=g(x); y means x=f(y), x=g(y).

axis

Physical rotation axis: horizontal means y=axis_at; vertical means x=axis_at.

axis_at

Finite scalar position of the axis.

breaks

Optional finite strictly increasing interior integration split points, for example known intersections. These are not found automatically.

quadrature

Integration rule: adaptive, trapezoid or simpson.

n

Initial number of equal cells for fixed rules; positive integer, even and at least two for Simpson. Ignored by the adaptive rule.

abs_tol, rel_tol

Nonnegative finite absolute and relative diagnostic tolerances; at least one must be positive. Adaptive integration also applies the tolerance restrictions of stats::integrate().

subdivisions

Positive integer maximum adaptive subinterval count; ignored by fixed rules.

Details

The region consists of segments between f and g at each independent coordinate, with g=0 by default. Washers apply for x/horizontal or y/vertical; shells apply for x/vertical or y/horizontal. Washer radii account for a region crossing its axis: the inner radius is zero and the outer radius is the larger distance. Otherwise use the two endpoint distances. No subtraction of squared signed heights is used. Shells integrate 2*pi*abs(t-axis_at)*abs(f(t)-g(t)); the interval must be entirely on one side of the axis, including an endpoint on it. Crossing the axis is rejected because shells from opposite sides can overlap; simply splitting and summing does not generally fix double counting. Sorted/equal bounds follow geometric-volume conventions. Quadrature may miss features; neither integration nor plots certify the region hypotheses. To recover rotation of the region between f and a shifted horizontal axis, explicitly supply g=function(t)axis_at (default g is zero).

Value

Plain list with type, sorted interval, breaks, variable, axis, axis_at, method (washers or shells), quadrature (rule name), estimate (nonnegative volume), integral (full segmented quadrature diagnostics), and note. Disks are washers with zero inner radius.

Examples

identity |> vc_revolution(c(0,1)) # cone: pi/3
(function(x)sqrt(1-x^2)) |> vc_revolution(c(-1,1)) # sphere: 4*pi/3

Compute signed tagged Riemann sums

Description

Compute signed tagged Riemann sums

Usage

vc_riemann(
  f,
  interval = NULL,
  n = 10L,
  method = c("midpoint", "left", "right"),
  partition = NULL
)

Arguments

f

Deterministic function accepting a real scalar and returning one finite real scalar. Vectorization is not required.

interval

Finite increasing bounds, or NULL with partition supplied.

n

Positive regular partition size; ignored with partition supplied.

method

One of midpoint, left or right. These are sample rules, not lower/upper Darboux sums.

partition

Optional vc_partition result. Its cells are reconstructed from breaks to validate consistency; interval, if given, must match.

Details

Computes sum f(sample_i)*width_i. Negative heights contribute negatively: this is not geometric area. All sampled values/contributions and the total must be finite. A lower Darboux sum uses the infimum on every cell; upper uses its supremum. Endpoint heights (or minima/maxima of finitely many samples) do not establish these extrema for general f. Riemann convergence requires appropriate integrability and vanishing mesh; a finite table or an increasing cell count is not a proof of convergence.

Value

Plain list with type, interval, partition, method, estimate, table (cell limits, width, midpoint, sample, value, contribution), and note.

Examples

function_to_sum <- function(x)x^2
function_to_sum |> vc_riemann(interval=c(0,2),n=100)

Compute signed double Riemann sums and sampled cell statistics

Description

Compute signed double Riemann sums and sampled cell statistics

Usage

vc_riemann2d(
  f,
  xlim = NULL,
  ylim = NULL,
  nx = 8L,
  ny = 8L,
  method = c("midpoint", "lower_left", "upper_right", "sample_min", "sample_max",
    "sample_mean"),
  partition = NULL,
  sample_n = 1L,
  lower = NULL,
  upper = NULL
)

Arguments

f

Scalar field accepting one x,y vector.

xlim, ylim

Finite increasing coordinate bounds; NULL with custom breaks.

nx, ny

Positive regular cell counts, ignored with corresponding breaks.

method

Midpoint, lower-left or upper-right tag; or finite sample minimum, maximum or mean. Sample extrema are NOT certified Darboux bounds.

partition

Optional vc_partition2d result, reconstructed from breaks.

sample_n

Positive subdivisions per coordinate for sample statistics; one samples the four corners. Ignored for single-tag rules.

lower, upper

Optional pair of scalar y-boundary functions of x. The supplied bounding box must contain their sampled bounds, in order.

Details

For nonrectangular regions computes the Riemann sum of f times the sampled domain indicator on the supplied box: outside samples give zero without evaluating f. Full rectangular cell areas remain in use; boundary cells are not exact clipped pieces. inside_fraction counts samples, not the fraction of geometric area. Membership/ordering are checked only at sampled x. Caller supplies a valid bounding box and justifies integrability of the zero extension and boundary behavior. Negative heights/contributions are signed, not geometric volumes. Finite statistics do not establish extrema, integrability or convergence.

Value

Plain list with estimate, partition, method, table including value, sample_x/sample_y, contribution, inside_fraction, and samples (per-cell tables of actual x,y,inside,value evaluations). Mean tags have NA coordinates.

Examples

(function(v)sum(v)) |> vc_riemann2d(c(0,1),c(0,1),nx=4,ny=4)

Tabulate double Riemann refinement

Description

Tabulate double Riemann refinement

Usage

vc_riemann2d_convergence(
  f,
  xlim,
  ylim,
  n_values = c(2L, 4L, 8L, 16L),
  method = "midpoint",
  sample_n = 1L,
  lower = NULL,
  upper = NULL,
  reference = NULL
)

Arguments

f

Scalar field accepting one x,y vector.

xlim, ylim

Finite increasing coordinate bounds; NULL with custom breaks.

n_values

Strictly increasing positive cell counts per coordinate.

method

Midpoint, lower-left or upper-right tag; or finite sample minimum, maximum or mean. Sample extrema are NOT certified Darboux bounds.

sample_n

Positive subdivisions per coordinate for sample statistics; one samples the four corners. Ignored for single-tag rules.

lower, upper

Optional pair of scalar y-boundary functions of x. The supplied bounding box must contain their sampled bounds, in order.

reference

Optional finite analytical value.

Value

List with complete results and table of n, cell count, mesh, estimate, change, error and abs_error. No limit is inferred from the table.

Examples

vc_riemann2d_convergence(function(v)sum(v),c(0,1),c(0,1),reference=1)

Tabulate Riemann refinement without claiming a limit

Description

Tabulate Riemann refinement without claiming a limit

Usage

vc_riemann_convergence(
  f,
  interval,
  n_values = c(4L, 8L, 16L, 32L, 64L),
  method = c("midpoint", "left", "right"),
  reference = NULL
)

Arguments

f

Deterministic function accepting a real scalar and returning one finite real scalar. Vectorization is not required.

interval

Finite increasing bounds, or NULL with partition supplied.

n_values

Strictly increasing positive integer regular cell counts.

method

One of midpoint, left or right. These are sample rules, not lower/upper Darboux sums.

reference

Optional finite scalar analytical/reference value. It is supplied by the caller, not inferred from the finest sum.

Value

Plain list with type, interval, method, results (full sum lists), table (n, mesh, estimate, change, error, abs_error) and note. First change and unavailable reference errors are NA; errors are estimate-reference.

Examples

f <- function(x)x^2
vc_riemann_convergence(f,c(0,2),reference=8/3)$table

Compute the secant through two points of a real function

Description

Compute the finite slope (f(x1)-f(x0))/(x1-x0). This is a secant slope, not a derivative or evidence of differentiability.

Usage

vc_secant(f, x0, x1)

Arguments

f

Deterministic function accepting a real scalar and returning one finite real scalar. Vectorization is not required.

x0

Finite real scalar giving the first abscissa.

x1

Finite real scalar giving a distinct second abscissa.

Details

Both function values, the displacement, the ordinate difference, and the quotient must be finite. Reversing the endpoints preserves the slope. No smoothness assumption is needed. Floating-point cancellation can affect the result; this operation does not estimate numerical error.

Value

Plain list with type ("secant"), x0, y0, x1, y1, dx, dy, slope, and note. The line is y0 + slope * (x - x0). No intercept is computed, avoiding unnecessary cancellation in an intercept representation.

Examples

vc_secant(function(x) x^2, 1, 2)
sin |> vc_secant(x0 = 0, x1 = 0.1)

Tabulate secants at decreasing steps

Description

Tabulate secants at decreasing steps

Usage

vc_secant_convergence(
  f,
  x0,
  steps = 2^(-(1:8)),
  method = c("forward", "backward", "central"),
  h = NULL,
  atol = 1e-08,
  rtol = 1e-04
)

Arguments

f

Deterministic function accepting a real scalar and returning one finite real scalar. Vectorization is not required.

x0

Finite real scalar evaluation point of the local model.

steps

Nonempty strictly decreasing positive finite real step vector. A single step is allowed. Steps are not silently sorted or deduplicated.

method

One of "central", "forward", or "backward".

h

Positive finite real initial derivative step, or NULL for the heuristic used by vc_derivative(), evaluated with x = x0.

atol

Nonnegative finite absolute tolerance for sensitivity comparisons.

rtol

Nonnegative finite relative tolerance for sensitivity comparisons.

Details

Recovers the decreasing-step procedure of legacy secant_tangent. Forward/backward secants join x0 to x0 plus/minus each step. Central secants join x0-step and x0+step: their lines pass through both endpoints, not generally through (x0,f(x0)). Reuses vc_secant and vc_tangent without changing their algorithms. Collapsed/nonfinite endpoints are errors. Numerical sequences and apparent agreement do not prove differentiability or convergence. Failed tangent diagnostics are retained without warnings.

Value

Plain list with type, x0, y0, method, steps, results (vc_secant objects), tangent (vc_tangent with full derivative diagnostics), table (step, left, right, slope, slope_difference), and note. slope_difference compares with a numerical tangent slope, not an exact derivative error.

Examples

(function(x)x^2) |> vc_secant_convergence(x0=1)
abs |> vc_secant_convergence(x0=0,method="central")

Sample the six faces of a nested Cartesian solid

Description

Sample the six faces of a nested Cartesian solid

Usage

vc_solid_cartesian(
  lower,
  upper,
  bottom,
  top,
  interval = NULL,
  n = 20L,
  n_u = 12L,
  n_v = 12L,
  partition = NULL
)

Arguments

lower, upper

Scalar y-boundary functions of x, ordered at sampled nodes.

bottom, top

Scalar z-boundary functions accepting one x,y vector.

interval

Finite increasing x bounds, or NULL with partition supplied.

n, n_u, n_v

Positive subdivisions in x, across y and across z.

partition

Optional vc_partition result for custom x strips.

Details

Reuses vc_region unchanged. Samples z bounds at every base grid node and retains exact shared endpoints on all face seams. Ordered bounds are checked at samples, not between nodes. Interpolated parametric faces may miss crossings or folds; this is not a certified watertight manifold. Degenerate sections/heights are allowed and can collapse face triangles. Disconnected sections need justified decomposition. No unused slice arguments are copied from the original API; it did not implement slices.

Value

Plain list with type solid_cartesian, base (full vc_region result), bottom/top matrices, v fractions and faces: x_min, x_max, y_lower, y_upper, z_lower, z_upper. Each face has finite x,y,z matrices with matching dimensions. No area, volume, normals or quadrature computed.

Examples

vc_solid_cartesian(function(x)0,function(x)1-x,function(v)0,
  function(v)1-sum(v),c(0,1),n=4,n_u=4,n_v=4)

Sample a cylindrical solid using stored parameter-box faces

Description

Sample a cylindrical solid using stored parameter-box faces

Usage

vc_solid_cylindrical(
  radial_lower,
  radial_upper,
  bottom,
  top,
  interval = NULL,
  n = 24L,
  n_u = 12L,
  n_v = 12L,
  partition = NULL
)

Arguments

radial_lower, radial_upper

Nonnegative ordered radius functions of theta.

bottom, top

Height functions of one theta,r vector, ordered at nodes.

interval

Increasing azimuth bounds in radians, span at most 2*pi; NULL with partition supplied. Geometry does not use reversed orientation.

n, n_u, n_v

Positive subdivisions in theta, radial blend and height blend.

partition

Optional vc_partition result for custom theta strips.

Details

Reuses vc_solid_cartesian unchanged, then maps stored theta,r,z to x=r*cos(theta), y=r*sin(theta), z=z. No boundary reevaluation is needed for this mapping; no area, normals, volume or quadrature are computed. Sampled boundary order does not certify between-node order or topology. At the axis patches can collapse. At a full turn angular cut patches can overlap and are not necessarily exterior boundary: all parameter patches remain stored and caller selects which to draw. Periodic boundary agreement is not inferred; nonperiodic endpoints can describe different seam sections. Coincident coordinates can differ by trigonometric roundoff. No exact closure, outward orientation or watertight manifold is certified.

Value

Plain list of type solid_cylindrical with parameter (full unchanged vc_solid_cartesian result in theta,r,z coordinates), physical Cartesian faces named theta_min, theta_max, radial_inner, radial_outer, z_lower, z_upper, full_turn flag (exact numeric span equals 2*pi), and note.

Examples

vc_solid_cylindrical(function(t)0,function(t)1,function(v)0,function(v)2,
  c(0,pi/2),n=4,n_u=3,n_v=3)

Sample spherical solids as stored parameter patches

Description

Sample spherical solids as stored parameter patches

Usage

vc_solid_spherical(
  polar_lower,
  polar_upper,
  radial_lower,
  radial_upper,
  interval = NULL,
  n = 24L,
  n_u = 16L,
  n_v = 8L,
  partition = NULL
)

Arguments

polar_lower, polar_upper

Ordered polar-angle functions of theta; sampled phi must lie in ⁠[0,pi]⁠, measured from positive z.

radial_lower, radial_upper

Ordered nonnegative radius functions of one theta,phi vector.

interval

Increasing azimuth theta bounds in radians; span at most 2*pi. NULL with partition supplied.

n, n_u, n_v

Positive subdivisions in theta, polar blend and radius blend.

partition

Optional vc_partition result for custom theta strips.

Details

Reuses the Cartesian parameter sampler and accepted spherical coordinate map unchanged. No volume, area, normals or quadrature computed. Exact pole sines are zero. Angular cuts and pole/origin degeneracies remain stored; cuts are not necessarily exterior boundary patches. Endpoint periodicity and pole consistency are not inferred from the angular ranges. Sampled ordering/shared endpoints cannot certify between-node behavior, exact closure, outward orientation or a watertight manifold. Curved patches are interpolated approximations. Original radial surface examples use constant polar bounds; theta-dependent polar bounds are also supported.

Value

Plain list of type solid_spherical with parameter (unchanged vc_solid_cartesian result in theta,phi,rho coordinates), Cartesian faces theta_min,theta_max,polar_lower,polar_upper,radial_inner,radial_outer, full_turn metadata (exact numeric span equals 2*pi) and note.

Examples

vc_solid_spherical(function(t)0,function(t)pi,function(v)1,function(v)2,
  c(0,2*pi),n=12,n_u=8,n_v=3)

Integrate a Cartesian field over a spherical-coordinate region

Description

Integrate a Cartesian field over a spherical-coordinate region

Usage

vc_spherical_integrate(
  f,
  interval,
  polar_lower,
  polar_upper,
  radial_lower,
  radial_upper,
  method = c("simpson", "trapezoid"),
  n_outer = 8L,
  n_middle = 16L,
  n_inner = 8L,
  abs_tol = 1e-08,
  rel_tol = 1e-08
)

Arguments

f

Scalar field accepting one vector in physical x,y,z order.

interval

Azimuth theta bounds in radians, reversed/equal allowed; absolute span at most 2*pi.

polar_lower, polar_upper

Functions of theta giving ordered polar angles phi in ⁠[0,pi]⁠, measured from the positive z axis.

radial_lower, radial_upper

Functions of one theta,phi vector giving nonnegative ordered radial bounds rho.

method

Simpson or trapezoid fixed quadrature.

n_outer, n_middle, n_inner

Initial cell counts, each refined internally.

abs_tol, rel_tol

Nonnegative diagnostic tolerances, one positive.

Details

Maps x=rho*sin(phi)*cos(theta), y=rho*sin(phi)*sin(theta), z=rho*cos(phi), using Jacobian rho^2*sin(phi). Exact endpoint poles use zero sine. Reuses vc_triple_integrate unchanged, preserving all diagnostics and heuristic error indicators. They are not certified bounds or evidence of change-of-variables hypotheses, integrability or ordering between nodes. All sampled fields must be finite, including origin and poles even where the Jacobian vanishes; supply justified continuous extensions explicitly. Azimuth reversal changes sign. Negative radii, sampled polar angles outside ⁠[0,pi]⁠ and spans above one azimuth turn are rejected. Equal widths skip deeper functions. No automatic singularity removal or adaptive nested rule.

Value

Full nested triple result of type spherical_integral. Stored engine coordinates are theta,phi,rho; f receives physical Cartesian x,y,z.

Examples

(function(v)1) |> vc_spherical_integrate(c(0,2*pi),function(t)0,function(t)pi,
  function(v)0,function(v)1,n_outer=2,n_middle=16,n_inner=2)

Search for multivariable stationary candidates from explicit starts

Description

Search for multivariable stationary candidates from explicit starts

Usage

vc_stationary_points(
  f,
  starts,
  bounds = NULL,
  assume_c2 = FALSE,
  h = NULL,
  hessian_h = NULL,
  tol_grad = 1e-05,
  tol_eigen = 1e-06,
  tol_merge = 1e-04,
  max_iter = 500L,
  atol = 1e-08,
  rtol = 1e-04,
  warn = TRUE
)

Arguments

f

Deterministic scalar field accepting ONE numeric vector and returning one finite real scalar. For f(x,y), supply an explicit wrapper function(v)f(v[1],v[2]); no automatic signature guessing is performed.

starts

One finite coordinate vector or a finite numeric matrix with one starting point per row, at least two columns. Optional column names are passed to f and must be unique/nonempty. No random starts are added.

bounds

Optional finite increasing n-by-2 numeric search-window matrix. This limits optimization, not the domain of f: central stencils may extend outside the window and must still be evaluable. Boundary hits are rejected.

assume_c2

Logical declaration by the caller that f is twice continuously differentiable in a neighborhood. Default FALSE prevents an extremum label; numerical stencils cannot verify this hypothesis.

h

NULL for per-coordinate vc_derivative heuristics, one positive finite step for all coordinates, or a positive finite vector of that dimension. No recycling of shorter vectors is allowed.

hessian_h

Positive scalar/vector second-difference step, or NULL for vc_hessian defaults. h controls first differences independently.

tol_grad

Positive absolute tolerance for the gradient norm and the finest left/right coordinate quotients. This is not an error bound.

tol_eigen

Positive absolute eigenvalue margin, enlarged by an empirical matrix refinement/roundoff allowance before classification.

tol_merge

Positive Euclidean distance below which accepted candidates are merged. Every run, including duplicates, remains in runs.

max_iter

Positive integer optimization limit passed to stats::optim.

atol

Nonnegative finite absolute tolerance for sensitivity comparisons.

rtol

Nonnegative finite relative tolerance for sensitivity comparisons.

warn

Logical scalar; warn when sensitivity diagnostics fail.

Details

Recovers the original critical_points_2d/critical_points_nd strategy of minimizing squared numerical gradient norm and merging duplicates. Reuses vc_gradient and vc_classify_stationary. Unbounded searches use Nelder-Mead; finite windows use L-BFGS-B. Hessians are never obtained by repeated differentiation of gradients. No random state is read or changed. Failed function/stencil evaluations receive a finite penalty and remain visible in the objective history; errors in a run do not erase other runs. History rows are objective evaluations, NOT Newton iterations or a claimed descent trajectory. Residual convergence is assessed independently of the optimizer's stopping code. Local minimization can stop at a nonzero residual, miss roots, leave unbounded windows or fail on poor scales. There is no completeness, convergence or global-extremum guarantee. Nondifferentiable critical points and constrained/boundary extrema are outside this stationary-point search. Supply scientifically chosen starts.

Value

Plain list with type, starts, bounds, points (rows of merged candidates), table (id, value, residual, classification), assessments, runs (start, terminal point, optimizer code/message, accepted, candidate_id, status, assessment and every objective evaluation), and note. Empty searches return a zero-row matrix/table. No optimizer code alone accepts a candidate; final stationarity/side checks are mandatory.

Examples

f <- function(v)v[1]^2+2*v[2]^2
f |> vc_stationary_points(rbind(c(.1,.2),c(-.2,.1)),assume_c2=TRUE)

Compare circulation and curl flux in Stokes' theorem

Description

Compare circulation and curl flux in Stokes' theorem

Usage

vc_stokes(
  field,
  surface,
  u_range,
  v_range,
  jacobian = NULL,
  curl = NULL,
  orientation = c("forward", "reverse"),
  h = NULL,
  curl_h = NULL,
  boundary_method = c("simpson", "trapezoid", "adaptive"),
  n_boundary = 16L,
  method = c("simpson", "trapezoid"),
  n_outer = 8L,
  n_inner = 8L,
  abs_tol = 1e-08,
  rel_tol = 1e-08
)

Arguments

field

Spatial vector field accepting one Cartesian vector.

surface

Function of one vector c(u,v) returning a finite Cartesian three-vector.

u_range, v_range

Finite strictly increasing parameter endpoint pairs.

jacobian

Optional function of c(u,v) returning a finite real 3 by 2 matrix, with surface derivatives as columns. Defaults to vc_jacobian().

curl

Optional function of position giving the three Cartesian curl components. Defaults to vc_curl().

orientation

Forward uses the u derivative crossed with the v derivative. Reverse negates the normal and reverses the boundary.

h

Optional numerical Jacobian step or two coordinate steps.

curl_h

Optional numerical step or three coordinate steps for curl.

boundary_method

Rule for vc_line_integral().

n_boundary

Initial fixed-rule cell count per boundary edge.

method

Simpson or trapezoid rule.

n_outer, n_inner

Initial cell counts, refined at both levels.

abs_tol, rel_tol

Nonnegative diagnostic tolerances, one positive.

Details

The boundary follows the four edges of the parameter rectangle. Forward traversal starts along increasing u at minimum v. A supplied surface Jacobian is also used for edge velocities. The caller supplies the smoothness, orientation and boundary hypotheses of Stokes' theorem. Multiple charts, trimming and topology inference are outside this API. Central stencils can leave the supplied domains. Agreement is diagnostic.

Value

List with boundary circulation, curl flux, signed difference, comparison tolerance, both quadrature results and derivative diagnostics.

Examples

patch <- function(p)c(p[1],p[2],p[1]+p[2])
vc_stokes(function(p)c(-p[2],p[1],0),patch,c(0,1),c(0,1),
  n_boundary=4,n_outer=2,n_inner=2)$curl_flux

Trace a spatial field trajectory with fixed-step RK4

Description

Trace a spatial field trajectory with fixed-step RK4

Usage

vc_streamline(f, seed, interval, n = 100L, time_dependent = FALSE)

Arguments

f

Function of one Cartesian vector, or of a vector and time when time_dependent is TRUE. Returns three finite Cartesian components.

seed

Initial Cartesian position at the first endpoint.

interval

Two finite times in traversal order.

n

Number of steps, at least one.

time_dependent

Use the signature f(position,time) for a pathline.

Details

Autonomous fields give streamlines. Reversed times integrate backward. Equal endpoints give one sample. The method uses the supplied field as velocity and has no adaptive error estimate or boundary events. The visualization sampling domain does not clip the trajectory.

Value

List with type streamline3d, samples t,x,y,z,speed and field mode.

Examples

vc_streamline(function(p)c(-p[2],p[1],0),c(1,0,0),c(0,pi/2))$samples

Approximate the lateral area generated by revolving a graph

Description

Approximate the lateral area generated by revolving a graph

Usage

vc_surface_area(
  f,
  interval,
  axis_at = 0,
  df = NULL,
  h = NULL,
  breaks = NULL,
  end_caps = FALSE,
  method = c("adaptive", "trapezoid", "simpson"),
  n = 32L,
  abs_tol = 1e-08,
  rel_tol = 1e-08,
  subdivisions = 100L
)

Arguments

f

Deterministic function accepting a real scalar and returning one finite real scalar. Vectorization is not required.

interval

Two finite real bounds, allowing reversed or equal bounds.

axis_at

Finite position of the parallel rotation axis in the dependent coordinate: y=axis_at for y=f(x), or x=axis_at for x=f(y).

df

Optional scalar derivative function, assumed mathematically correct. NULL reuses vc_derivative() with central differences.

h

Optional positive finite numerical derivative step.

breaks

Optional finite strictly increasing interior integration split points, for example known intersections. These are not found automatically.

end_caps

Logical; add two circular end disks with endpoint radii abs(f(t)-axis_at). This assumes the filled region between this graph and its axis. It is not the cap rule for a two-graph annular region.

method

Quadrature rule: trapezoid, Simpson, or adaptive QUADPACK through stats::integrate(). Improper infinite bounds are not supported.

n

Initial number of equal cells for fixed rules; positive integer, even and at least two for Simpson. Ignored by the adaptive rule.

abs_tol, rel_tol

Nonnegative finite absolute and relative diagnostic tolerances; at least one must be positive. Adaptive integration also applies the tolerance restrictions of stats::integrate().

subdivisions

Positive integer maximum adaptive subinterval count; ignored by fixed rules.

Details

Integrates ⁠2*pi*abs(f(t)-axis_at)*sqrt(1+f'(t)^2)⁠. This is the surface generated by one graph, not automatically the entire boundary of a washer/shell solid between two graphs. Parameterization must cover the surface without multiplicity for geometric-area interpretation. Caps are excluded by default. Equal bounds give zero lateral and cap areas without evaluating endpoints; coincident end disks are not counted twice.

Value

A surface_area list with the same diagnostics as vc_arc_length() and axis_at, lateral_area, cap_area, end_caps. Estimate is lateral area plus requested caps; integral diagnostics describe only the lateral part.

Examples

identity |> vc_surface_area(c(0,1),df=function(x)1) # pi*sqrt(2)

Integrate a scalar density or oriented flux on a graph

Description

Integrate a scalar density or oriented flux on a graph

Usage

vc_surface_graph_integral(
  graph,
  x_range,
  y_range,
  f = NULL,
  type = c("scalar", "flux"),
  gradient = NULL,
  orientation = c("up", "down"),
  h = NULL,
  method = c("simpson", "trapezoid"),
  n_outer = 8L,
  n_inner = 8L,
  abs_tol = 1e-08,
  rel_tol = 1e-08
)

Arguments

graph

Function of one vector c(x,y) returning the scalar height.

x_range, y_range

Finite endpoint pairs for the Cartesian base rectangle.

f

NULL for area, a scalar density for scalar integration, or a three-component vector field for flux. Functions accept one Cartesian vector.

type

Scalar integration or oriented flux.

gradient

Optional function of c(x,y) returning the two height partials.

orientation

Up uses the normal with positive z component. Down negates flux. Scalar integration is unchanged.

h

Optional numerical Jacobian step or two coordinate steps.

method

Simpson or trapezoid rule.

n_outer, n_inner

Initial cell counts, refined at both levels.

abs_tol, rel_tol

Nonnegative diagnostic tolerances, one positive.

Value

The vc_surface_integral() result with up/down orientation.

Examples

vc_surface_graph_integral(function(p)sum(p),c(0,1),c(0,1),
  f=function(p)c(0,0,1),type="flux",n_outer=2,n_inner=2)$estimate

Integrate area, scalar density or flux on a parameterized surface

Description

Integrate area, scalar density or flux on a parameterized surface

Usage

vc_surface_integral(
  surface,
  u_range,
  v_range,
  f = NULL,
  type = c("scalar", "flux"),
  jacobian = NULL,
  orientation = c("forward", "reverse"),
  h = NULL,
  method = c("simpson", "trapezoid"),
  n_outer = 8L,
  n_inner = 8L,
  abs_tol = 1e-08,
  rel_tol = 1e-08
)

Arguments

surface

Function of one vector c(u,v) returning a finite Cartesian three-vector.

u_range, v_range

Two finite endpoints for each parameter. Integration uses increasing bounds. Equal bounds give zero without surface evaluations.

f

NULL for area, a scalar density for scalar integration, or a three-component vector field for flux. Functions accept one Cartesian vector.

type

Scalar integration or oriented flux.

jacobian

Optional function of c(u,v) returning a finite real 3 by 2 matrix, with surface derivatives as columns. Defaults to vc_jacobian().

orientation

Forward uses the u derivative crossed with the v derivative. Reverse negates flux. It has no effect on scalar integration.

h

Optional numerical Jacobian step or two coordinate steps.

method

Simpson or trapezoid rule.

n_outer, n_inner

Initial cell counts, refined at both levels.

abs_tol, rel_tol

Nonnegative diagnostic tolerances, one positive.

Details

Scalar integration uses the norm of the cross product and counts parameterization multiplicity. Flux uses the oriented, unnormalized cross product. A zero cross product contributes zero without requiring a unit normal. Numerical stencils can leave the parameter domain. The quadrature diagnostics omit derivative error. Samples do not establish smoothness, regularity, injectivity or a globally consistent orientation.

Value

List with estimate, full nested quadrature diagnostics, sample parameters, positions, area factors, signed integrands and numerical derivative sensitivity. Supplied derivatives have NA sensitivity.

Examples

vc_surface_integral(function(p)c(p[1],p[2],p[1]+p[2]),c(0,1),c(0,1),
  n_outer=2,n_inner=2)$estimate

Sample a rectangular parameter patch in space

Description

Sample a rectangular parameter patch in space

Usage

vc_surface_sample(surface, u_range, v_range, n_u = 31L, n_v = 31L)

Arguments

surface

Function of one vector c(u,v) returning a finite Cartesian three-vector.

u_range, v_range

Finite endpoint pairs in traversal order.

n_u, n_v

Number of nodes in each parameter, at least two. Equal endpoints produce a single node along that axis.

Value

List with type surface3d, parameter nodes u and v, and grid matrices x, y, z with v in rows and u in columns.

Examples

vc_surface_sample(function(p)c(p[1],p[2],prod(p)),c(0,1),c(0,1),n_u=3,n_v=3)

Construct an approximate tangent line

Description

Use vc_derivative() to construct the local line y0 + slope * (x - x0). The numerical line is not proof that a mathematical tangent exists.

Usage

vc_tangent(
  f,
  x0,
  method = c("central", "forward", "backward"),
  h = NULL,
  atol = 1e-08,
  rtol = 1e-04,
  warn = TRUE
)

Arguments

f

Deterministic function accepting a real scalar and returning one finite real scalar. Vectorization is not required.

x0

Finite real scalar evaluation point of the local model.

method

One of "central", "forward", or "backward".

h

Positive finite real initial derivative step, or NULL for the heuristic used by vc_derivative(), evaluated with x = x0.

atol

Nonnegative finite absolute tolerance for sensitivity comparisons.

rtol

Nonnegative finite relative tolerance for sensitivity comparisons.

warn

Logical scalar; warn when sensitivity diagnostics fail.

Details

A two-sided tangent requires differentiability at x0. One-sided methods instead construct a one-sided approximation, which may differ from a two-sided tangent. All limitations of vc_derivative apply.

Value

Plain list with type ("tangent"), x0, y0, slope, derivative (the full vc_derivative result), and note. Inspect derivative$reliable and its diagnostics before interpreting the slope. Failed diagnostics retain the approximation, with a warning unless warn = FALSE.

Examples

vc_tangent(function(x) x^2, 1)
sin |> vc_tangent(x0 = 0)
vc_tangent(abs, 0, warn = FALSE)$derivative$reliable

Numerical Taylor approximations of order one or two

Description

Construct P(x) = f(x0) + d1*(x-x0) + d2*(x-x0)^2/2 (order two), or omit the quadratic term for order one. Derivatives are numerical.

Usage

vc_taylor(
  f,
  x0,
  order = 2L,
  x = NULL,
  method = c("central", "forward", "backward"),
  h = NULL,
  h2 = NULL,
  atol = 1e-08,
  rtol = 1e-04,
  warn = TRUE
)

Arguments

f

Deterministic function accepting a real scalar and returning one finite real scalar. Vectorization is not required.

x0

Finite real scalar evaluation point of the local model.

order

Integer 1 or 2. Higher orders are not implemented.

x

Optional nonempty finite real vector at which to compare f and P. NULL leaves comparison empty; the returned polynomial is still evaluable.

method

One of "central", "forward", or "backward".

h

Positive finite real initial derivative step, or NULL for the heuristic used by vc_derivative(), evaluated with x = x0.

h2

Positive finite initial step for the second derivative. NULL uses max(1, abs(x0)) * .Machine$double.eps^(1/4). Ignored for order one, but a supplied value must still be valid. h controls only the first derivative.

atol

Nonnegative finite absolute tolerance for sensitivity comparisons.

rtol

Nonnegative finite relative tolerance for sensitivity comparisons.

warn

Logical scalar; warn when sensitivity diagnostics fail.

Details

The first derivative reuses vc_derivative() with its selected method and diagnostics. Order two uses a direct three-point stencil, never repeated numerical differentiation. With actual representable displacements a = x0-left and b = right-x0, the second derivative is 2 * ((f(right)-f(x0))/b - (f(x0)-f(left))/a) / (a+b). Equal spacing gives the usual centered second difference, with nominal second-order truncation for sufficiently smooth functions. Asymmetric rounded stencils can reduce that order.

Second-derivative steps h2, h2/2, h2/4 are compared using the same absolute/relative tolerance rule as vc_derivative(). An additional roundoff indicator is 4epsilonmax(abs(stencil values))/min(a,b)^2. The finest indicator must not exceed atol + rtol*abs(d2). This is a conservative floating-point scale heuristic, not a rigorous error bound. The finest estimate is retained even if checks fail. Order two always requires finite values on both sides, even with a one-sided first derivative.

A genuine Taylor interpretation assumes the required derivatives exist near x0. Numerical checks do not establish this assumption. Comparison errors are sampled differences f(x)-P(x), not certified remainder bounds. Optional comparison points with failed/nonfinite function evaluations have value and error NA, with explicit status; evaluation warnings are suppressed. Nonfinite polynomial values are likewise NA in the comparison table. Large offsets, cancellation and unresolved oscillations can evade checks. Checks are conservative: the existing first-derivative side comparison can flag smooth stationary points, and the second-derivative roundoff indicator can flag a nonzero constant with exactly zero curvature. Such results are retained with failed diagnostics, not declared invalid.

Value

Plain list with type, x0, y0, order, coefficients (in powers of x-x0, including the constant), polynomial (a vectorized function), derivative (full vc_derivative result), second_derivative (diagnostics list or NULL), comparison (data frame or NULL), reliable and note. The comparison columns are x, distance, value, approximation, error, abs_error and status. reliable means only that applicable numerical checks passed. The polynomial rejects invalid inputs and overflowing evaluations. second_derivative contains estimate, h, diagnostics (step, left_step, right_step, estimate, roundoff_indicator), changes, stable, resolved, and reliable. stable compares successive estimates; resolved checks the finest roundoff indicator; reliable is their conjunction.

Examples

a <- vc_taylor(exp, 0, order = 2, x = c(-0.2, 0, 0.2))
a$comparison
a$polynomial(c(0, 0.1))
sin |> vc_taylor(x0 = 0, order = 1, x = c(0, 0.2))

Integrate over a nested Cartesian solid

Description

Integrate over a nested Cartesian solid

Usage

vc_triple_integrate(
  f,
  interval,
  middle_lower,
  middle_upper,
  inner_lower,
  inner_upper,
  order = c("zyx", "zxy", "yzx", "yxz", "xzy", "xyz"),
  method = c("simpson", "trapezoid"),
  n_outer = 8L,
  n_middle = 8L,
  n_inner = 8L,
  abs_tol = 1e-08,
  rel_tol = 1e-08
)

Arguments

f

Scalar field accepting one vector in physical x,y,z order.

interval

Finite outer bounds, reversed or equal allowed.

middle_lower, middle_upper

Functions of the outer coordinate giving ordered middle bounds.

inner_lower, inner_upper

Functions accepting a two-vector in outer,middle order, giving ordered inner bounds.

order

Integration order from inner to outer; a permutation of xyz.

method

Simpson or trapezoid fixed quadrature.

n_outer, n_middle, n_inner

Initial cell counts, each refined internally.

abs_tol, rel_tol

Nonnegative diagnostic tolerances, one positive.

Details

Reuses unchanged scalar and double quadrature engines. Absolute finest outer weights propagate each double-slice error indicator; this sum plus outer refinement error is heuristic, not a certified bound. All slice flags also gate tolerance_met. Finite sampling does not prove Fubini hypotheses, integrability or ordering between sampled sections. Caller supplies a justified nested region and splits known singularities. Reversed outer bounds change sign; reversed sampled middle/inner bounds are rejected. Equal widths skip deeper functions. Signed integrals need not be geometric volumes. Storage and evaluations grow cubically with resolution. No cylindrical/spherical transformation or adaptive rule.

Value

List containing estimate, error_estimate, tolerance_met, outer (full vc_integrate result), slices (cached full vc_double_integrate results), outer_nodes, projection, order and interval.

Examples

(function(v)1) |> vc_triple_integrate(c(0,1),function(x)0,function(x)1-x,
  function(v)0,function(v)1-sum(v),n_outer=2,n_middle=2,n_inner=2)

Sample a spatial vector field in a nested Cartesian solid

Description

Sample a spatial vector field in a nested Cartesian solid

Usage

vc_vector_field_sample(
  f,
  lower,
  upper,
  bottom,
  top,
  interval = NULL,
  n = 8L,
  n_u = 6L,
  n_v = 6L,
  partition = NULL
)

Arguments

f

Function of one Cartesian vector returning three finite components.

lower, upper

Scalar y-boundary functions of x, ordered at sampled nodes.

bottom, top

Scalar z-boundary functions accepting one x,y vector.

interval

Finite increasing x bounds, or NULL with partition supplied.

n, n_u, n_v

Positive subdivisions in x, across y and across z.

partition

Optional vc_partition result for custom x strips.

Details

Subdivisions include both endpoints and z varies fastest. The sampled solid validates boundary order at the nodes. Degenerate fibers can repeat positions.

Value

List with type vector_field3d and samples x,y,z,u,v,w,magnitude.

Examples

vc_vector_field_sample(function(p)c(-p[2],p[1],0),function(x)-1,
  function(x)1,function(p)-1,function(p)1,c(-1,1),n=2,n_u=2,n_v=1)