Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
285 changes: 285 additions & 0 deletions docs/visualization/finite-difference.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,285 @@
# Finite-difference data

A finite-difference code writes samples on a logical lattice: at the grid's
points, at its cell centres, or, in a staggered scheme, each component on its
own faces or edges. To analyse its output, keep three things apart:

- **where each value is and what it is**: a point sample, or an average over a
cell;
- **the function you choose between the samples** to contour, probe, render or
trace: a *reconstruction*;
- **the solver's difference operators**, which are not derivatives of that
function.

Trilinear interpolation is a good default reconstruction for pictures, but it
is a choice, not something the solver said. Here is the difference on the
simplest case, `u = x²` sampled at spacing 0.25:

<!-- tack-check: fd-first -->
```python
import numpy as np

import tack
import tack.dataset as td

tack.set_default_device("cpu")

# u = x**2 sampled at the points of a line of spacing 0.25.
data = td.uniform_grid((9,), spacing=(0.25, 1.0, 1.0), dtype=tack.f64)
x = data.positions()[:, 0]
data.fields["u"] = td.Field(td.H1(data), tack.array(x**2))

# The solver's operator: the centred second difference, exactly 2 inside.
d2 = td.finite_differences(data, "u", derivative=2)
uxx = d2.values.numpy()[:, 0] # d2u/dx2 of the nine
print(uxx[1:-1])

# The reconstruction between the samples: H1's linear interpolant, the chord.
half = np.array([[0.125, 0.0, 0.0], [0.375, 0.0, 0.0]])
chord = td.probe(data, half).fields["u"].values.numpy()
print(chord, half[:, 0] ** 2)

assert np.allclose(uxx[1:-1], 2.0)
assert np.allclose(chord - half[:, 0] ** 2, 0.25**2 / 4)
```

```text
[2. 2. 2. 2. 2. 2. 2.]
[0.03125 0.15625] [0.015625 0.140625]
```

The centred difference gives the second derivative exactly. The linear
interpolant through the same samples is straight inside each interval, so its
second derivative there is 0, and midway between two samples it lies above
the parabola by `h²/4`. Neither is wrong: they answer different questions.
Pick the operator for derived quantities, and the reconstruction for pictures
and probes.

## What Tack has for it

| Task | Use |
|---|---|
| A grid without stored connectivity or point positions | [`uniform_grid`](../vis-guide/reference/data-model.md), `rectilinear_grid` |
| Samples at the points, read trilinearly | `Field(H1(data), values)` |
| One value a cell, read as constant over it | `Field(Constant(data), values)` |
| Samples at the cell centres, read trilinearly between them | a grid shifted by half a cell, [below](#samples-at-cell-centres) |
| The solver's derivatives, order 2, 4 or 6 | [`finite_differences`](../vis-guide/reference/algorithms.md#tack.dataset.algorithms.finite_differences.finite_differences) |
| Derivatives of the reconstruction | [`gradients`](../vis-guide/reference/algorithms.md#tack.dataset.algorithms.gradients.gradients) |
| Face fluxes and their balances | [Finite-volume data and fluxes](finite-volume.md) |

An image (`uniform_grid`) computes its points' positions from its origin and
spacing, and a rectilinear grid from its three axes; neither stores
connectivity. A curvilinear grid stores its points' positions only. So a
lattice of samples costs its values and nothing more.

## Point samples and cell averages

A value at a point is the field there. A value for a cell may be either the
field at the cell's centre (a point sample) or its mean over the cell (an
average, as a finite-volume code writes). The two agree to second order for a
smooth field, and differ for anything else.

Tack's spaces say how a value is read, not which of these it is:

- `H1(data)` at the points: trilinear between them.
- `Constant(data)` on the cells: the same value over the whole cell. That is
the right reading for an average, and a coarse one for a point sample.

`Values(data, "points")` and `Values(data, "cells")` hold values with no basis.
But a filter that needs one (`contour`, `probe`, `gradients`) reads point
`Values` as `H1` and cell `Values` as `Constant`. So they choose the trilinear
and the piecewise-constant reconstruction for you. To make the choice yourself,
put the values in `H1` or `Constant`, or in a grid of their own.

## Samples at cell centres

When a solver's point samples are at its cell centres, they are the points of
another lattice, one shifted by half a cell with one point fewer along each
axis. Make that grid and read them trilinearly there:

<!-- tack-check: fd-centres -->
```python
import numpy as np

import tack
import tack.dataset as td

tack.set_default_device("cpu")

# The solver's 4 x 4 cells of size 0.25 on [0, 1]^2, a sample at each centre.
h = 0.25
cells = td.uniform_grid((5, 5), spacing=(h, h, 1.0), dtype=tack.f64)
centres = (np.arange(4) + 0.5) * h
cx, cy = np.meshgrid(centres, centres) # x fastest, as the grid
samples = (cx + 2 * cy).reshape(-1)

# Read as constant over each solver cell: the cells keep their own values.
cells.fields["t"] = td.Field(td.Constant(cells), tack.array(samples))

# Read trilinearly: the centres are the points of a grid shifted by h / 2.
shifted = td.uniform_grid((4, 4), origin=(h / 2, h / 2, 0.0), spacing=(h, h, 1.0),
dtype=tack.f64)
shifted.fields["t"] = td.Field(td.H1(shifted), tack.array(samples))

where = np.array([[0.5, 0.5, 0.0], [0.05, 0.5, 0.0]])

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(0.5, 0.5) is a vertex shared by four solver cells, so the constant reading's 1.125 is whichever cell probe picks. A point inside one cell would make the comparison read cleanly.

constant = td.probe(cells, where)
linear = td.probe(shifted, where)
print(constant.fields["t"].values.numpy(), linear.fields["t"].values.numpy(),
linear.fields["valid"].values.numpy())

assert np.allclose(linear.fields["t"].values.numpy()[0], 1.5)
assert linear.fields["valid"].values.numpy().tolist() == [1, 0]
```

```text
[1.125 0.875] [1.5 0. ] [1 0]
```

The trilinear reading gives the linear field exactly at `(0.5, 0.5)`, where the
constant reading gives one cell's sample. But the shifted grid covers only the
centres' hull: the strip within half a cell of the boundary, where
`(0.05, 0.5)` lies, is outside it, so `probe` marks that point not valid. To
cover the whole domain the solver's ghost samples are needed, or a rule for
extending past the last centre. Neither reading recovers the function the
solver had between its samples: each is a choice.

## Derivatives: the operator or the reconstruction

[`finite_differences`](../vis-guide/reference/algorithms.md#tack.dataset.algorithms.finite_differences.finite_differences)
takes the gradient (`derivative=1`) or the second derivatives (`derivative=2`)
of point or cell data on images, rectilinear and curvilinear grids. Its
differences are along the grid's index axes, of order 2, 4 or 6, turned to
world axes through the positions' own differences, so one rule serves every
kind of grid. At order 2 it gives VTK's `vtkGradientFilter` on structured
data. [`gradients`](../vis-guide/reference/algorithms.md#tack.dataset.algorithms.gradients.gradients)
differentiates the field's reconstruction instead: the trilinear function in
each cell.

On a smooth field the error of `finite_differences` falls as the spacing to its
order:

<!-- tack-check: fd-orders -->
```python
import numpy as np

import tack
import tack.dataset as td

tack.set_default_device("cpu")

# u = sin(x) on [0, pi] in 33 points, and its derivative cos(x).
data = td.uniform_grid((33,), spacing=(np.pi / 32, 1.0, 1.0), dtype=tack.f64)
x = data.positions()[:, 0]
data.fields["u"] = td.Field(td.H1(data), tack.array(np.sin(x)))

inside = slice(3, -3) # away from the one-sided ends
errors = {}
for order in (2, 4, 6):
du = td.finite_differences(data, "u", order=order).values.numpy()[:, 0]
errors[order] = np.abs(du - np.cos(x))[inside].max()
print({k: f"{v:.1e}" for k, v in errors.items()})

assert errors[2] > 100 * errors[4] > 100 * errors[6]
```

```text
{2: '1.5e-03', 4: '3.0e-06', 6: '6.1e-09'}
```

Points:

- **Edges.** At order 2 the edges take the narrowest stencils, as VTK does (a
first derivative from two points, so first order there). Orders 4 and 6 take
one-sided stencils of their own order.
- **Hidden points and cells** (`Ghosts.HIDDENPOINT`, `HIDDENCELL`) hold no
values: they bound the stencils as the grid's edges do.
- **Ghost layers** widen the stencils at a piece's boundary, so a piece's owned
points get the whole grid's derivatives once the ghosts are refreshed
([Filters over pieces](over-pieces.md)).
- **Cell data** is differenced over the cells' centres.
- **Layout.** The gradient of a vector is `3k` values a point, `d(u_i)/d(x_j)`
at `3 * i + j`, as `gradients` lays it out, so
[`flow_quantities`](derive.md) takes either.

## Staggered components

In a staggered scheme each component has its own lattice: a MAC grid's `u`, `v`
and `w` on the x-, y- and z-faces, or a Yee lattice's electric field on edges
and magnetic field on faces. Such arrays are not the components of a vector at
one place, and magnitude, energy, cross products or particle tracing need them
brought to a common location first.

Tack does not hold staggered layouts yet. A structured grid's faces are
numbered as any mesh's are, not in blocks of x-, y- and z-faces, so a solver's
array of x-face values does not line up with `Values(data, "faces")`. Today,
bring the components to the cell centres yourself, and say how: averaging the
two faces of each cell along its axis is the usual choice. A kernel does it on
the device:

<!-- tack-check: fd-staggered -->
```python
import numpy as np

import tack
import tack.dataset as td

tack.set_default_device("cpu")


@tack.kernel
def face_means(u, v, nx, ny, out):
# Cell (i, j)'s velocity: the mean of its two x-faces' u and two y-faces' v.
# u is (nx + 1) x ny x-faces, v is nx x (ny + 1) y-faces, x fastest.
for c in range(nx * ny):
i = c % nx
j = c // nx
a = 0.5 * (u[j * (nx + 1) + i] + u[j * (nx + 1) + i + 1])
b = 0.5 * (v[j * nx + i] + v[(j + 1) * nx + i])
out[c] = tack.vec3(a, b, 0.0)


# A MAC grid of 4 x 3 cells of size 1: u = x on the x-faces, v = -y on the y-faces.
nx, ny = 4, 3
data = td.uniform_grid((nx + 1, ny + 1), dtype=tack.f64)
u = np.tile(np.arange(nx + 1.0), ny) # x at each x-face
v = -np.repeat(np.arange(ny + 1.0), nx) # -y at each y-face
velocity = tack.empty((nx * ny,), tack.vec3(tack.f64))
face_means(tack.array(u), tack.array(v), nx, ny, velocity)
data.fields["velocity"] = td.Field(td.Constant(data), velocity)

print(data.fields["velocity"].values.numpy()[:2])
assert np.allclose(velocity.numpy()[:, 0], np.tile(np.arange(nx) + 0.5, ny))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Check v too, since the y-faces' indexing is the easier one to get wrong.

```

```text
[[ 0.5 -0.5 0. ]
[ 1.5 -0.5 0. ]]
```

The averaged field is exact for a linear velocity. It is a reconstruction, as
the cell-centre readings above are: say which one you used when you report
derived quantities. If the components are stored at different times, as a Yee
scheme's electric and magnetic fields are, combining them needs a common time
too.

## Details

- **Units.** Give the grid its spatial unit (`unit=`) and the fields theirs:
a gradient's unit is the field's over the spatial unit (K/m for a
temperature on a grid in metres), a second derivative's over its square.
- **Integers.** Integer samples are differenced in floating point (f32 on an
f32 grid).
- **Where this is going.** The plan for finite-difference data
([#321](https://github.com/Kitware/tack/issues/321)) adds a space for lattice
samples that says where its values are and whether they are averages, with no
implicit reconstruction; explicit reconstructions; the difference operators on
those lattices with declared boundary rules; and staggered components brought
together explicitly.

## Where to go next

- [Finite-volume data and fluxes](finite-volume.md), for values on faces and
their balances.
- [Derive](derive.md), for gradients and flow quantities.
- [Fields](../data/fields.md), for spaces and what each one reads.
- [Filters over pieces](over-pieces.md), for ghost layers.
3 changes: 3 additions & 0 deletions docs/visualization/finite-volume.md
Original file line number Diff line number Diff line change
Expand Up @@ -274,3 +274,6 @@ upwind mass outflow, and the traces and jumps.
or a higher-order representation.
- [Derive](derive.md) covers gradients and flow quantities from fields with a
basis.
- [Finite-difference data](finite-difference.md) covers samples on a lattice:
where each value is, the reconstruction between them, and difference
operators.
3 changes: 2 additions & 1 deletion docs/visualization/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,8 @@ algorithm's full signature and its Viskores counterpart.
Other tasks have pages of their own:
[point clouds and particles](points-and-particles.md) (VTK's
vtkFiltersPoints), [AMR and octrees](adaptive-data.md),
[finite-volume fluxes](finite-volume.md), [filters over pieces](over-pieces.md)
[finite-volume fluxes](finite-volume.md), [finite-difference
data](finite-difference.md), [filters over pieces](over-pieces.md)
(`vtkGhostCellsGenerator`, `vtkGenerateGlobalIds`, `vtkMergeBlocks`), and
[steps over time](over-time.md) (`vtkParticlePathFilter`,
`vtkStreaklineFilter`, temporal statistics).
Expand Down
1 change: 1 addition & 0 deletions mkdocs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,7 @@ nav:
- Points and particles: visualization/points-and-particles.md
- Adaptive data: visualization/adaptive-data.md
- Finite-volume data and fluxes: visualization/finite-volume.md
- Finite-difference data: visualization/finite-difference.md
- At scale and over time:
- Filters over pieces: visualization/over-pieces.md
- Steps over time: visualization/over-time.md
Expand Down