CW-ToF: antithetic sampling and the modulation wavelength

This tutorial compares naive and antithetic sampling of a CW-ToF measurement at equal time for three modulation wavelengths, with the antithetic path found by Newton’s method on the barycentric coordinates of the vertex’s triangle. It builds on CW-ToF rendering (offline), which explains the render graph.

Naive and antithetic CW-ToF rendering at equal time for the wavelengths 0.02, 0.1 and 1, with references

The antithetic path

CWToFPathTracerInline weights each path by \(\cos(2\pi\,\ell / \lambda)\), with \(\ell\) the path length. With antithetic sampling, every BSDF-sampled vertex \(y\) after the primary hit gets an antithetic vertex \(y'\) on its surface such that the path is half a wavelength longer or shorter, \(\ell(y') = \ell(y) \pm \lambda / 2\), where the cos has the opposite sign. The two are combined with multiple importance sampling (see Antithetic sampling).

\(y'\) has two coordinates on the surface and one condition on the path length, so one more condition fixes it: the gauge. Here the antithetic vertex is found with shiftMappingMethod = barycentric:

  • The unknowns are the barycentric coordinates of \(y'\) on \(y\)’s triangle, so \(y'\) stays on the triangle (the shift fails if it would leave it).

  • Newton’s method solves the length condition together with gaugeMode = avg_grad: \(y'\) moves along the average of the path-length gradients at \(y\) and \(y'\), which makes the backward shift return to \(y\).

  • The Jacobian of the map, which multiple importance sampling needs, comes from the implicit function theorem at the solution.

The default radial shift solves the same condition with a 1D search along a ray on the vertex’s plane, from the point of the plane with the shortest path (found in closed form); it is a little faster and exactly invertible. Newton’s method is local, so rarely (near the shortest path, or with a ray chart on curved surfaces) the backward shift reaches another solution; shiftRoundTripCheck removes most of the small bias this leaves, at the cost of a second shift.

1. Load the scene

import time

import matplotlib
matplotlib.use("Agg")  # no window
import matplotlib.pyplot as plt
import numpy as np
import falcorcomp as falcor

testbed = falcor.Testbed(create_window=False)
testbed.load_scene("cornell-box/scene-v4-nolight.pbrt")
testbed.resize_frame_buffer(512, 512)
testbed.scene.camera.aspectRatio = 1.0
testbed.clock.pause()

SECONDS = 0.3              # rendering time for each method
REFERENCE_FRAMES = 16384   # 16384 frames x 16 spp for each reference
WAVELENGTHS = [0.02, 0.1, 1.0]

2. Build the render graph

The graph is that of CW-ToF rendering, with one sample per pixel per frame, so that the frame counts measure time finely. The two methods differ only in the antithetic options.

CWTOF = {
    "samplesPerPixel": 1, "maxBounces": 4,
    "computeDirect": False,  # indirect light only
    "waveform": "cos",
    "useSingleChannel": True, "singleChannel": "luminance",
}
NAIVE = {"useAntitheticSampling": False}
# The antithetic vertex is found by Newton's method on the triangle's barycentric
# coordinates, moving along the average path-length gradient.
ANTITHETIC = {"useAntitheticSampling": True,
              "shiftMappingMethod": "barycentric", "gaugeMode": "avg_grad"}


def create_graph(properties):
    graph = testbed.create_render_graph("CWToF")
    graph.create_pass("VBuffer", "VBufferRT", {"samplePattern": "Center", "sampleCount": 1})
    graph.create_pass("Light", "LaserLight", {
        "isLightSourceLaser": False, "laserCollocated": True, "laserPower": [10.0, 10.0, 10.0],
    })
    graph.create_pass("Tracer", "CWToFPathTracerInline", {**CWTOF, **properties})
    graph.create_pass("Accumulate", "AccumulatePass", {"precisionMode": "SingleCompensated"})
    graph.add_edge("VBuffer.vbuffer", "Tracer.vbuffer")
    graph.add_edge("VBuffer.viewW", "Tracer.viewW")
    graph.add_edge("Light", "Tracer")
    graph.add_edge("Tracer.color", "Accumulate.input")
    graph.mark_output("Accumulate.output")
    return graph


3. Render each method for the same time

Each method compiles its shaders, warms up for a second, then renders for 0.3 seconds; every frame waits for the GPU, so the time includes all of its work.

def render(graph, seconds=None, frames=None):
    testbed.render_graph = graph
    testbed.frame()  # compiles the shaders
    start = time.perf_counter()
    while time.perf_counter() - start < 1.0:  # warm up the GPU
        testbed.frame()
    graph.get_pass("Accumulate").reset()
    testbed.device.wait()
    count, elapsed = 0, 0.0
    while (elapsed < seconds) if seconds is not None else (count < frames):
        start = time.perf_counter()
        testbed.frame()
        testbed.device.wait()  # include the frame's GPU time
        elapsed += time.perf_counter() - start
        count += 1
    return graph.get_output("Accumulate.output").to_numpy()[..., 0], count


def relative_mse(image, reference):
    return float(np.mean((image - reference) ** 2) / np.mean(reference ** 2))


4. Compare at each wavelength

rows = []
for wavelength in WAVELENGTHS:
    reference, _ = render(create_graph({**NAIVE, "modulationWavelength": wavelength,
                                        "samplesPerPixel": 16}), frames=REFERENCE_FRAMES)
    results = []
    for name, method in [("Naive", NAIVE), ("Antithetic", ANTITHETIC)]:
        image, spp = render(create_graph({**method, "modulationWavelength": wavelength}),
                            seconds=SECONDS)
        error = relative_mse(image, reference)
        print(f"wavelength {wavelength}: {name}, {spp} spp, relMSE {error:.4f}")
        results.append((f"{name}: {spp} spp\nrelMSE {error:.3g}", image))
    rows.append((wavelength, results + [("Reference", reference)]))

Wavelength

Naive (0.3 s)

Antithetic (0.3 s)

Naive relMSE

Antithetic relMSE

0.02

525 spp

301 spp

1.97

0.288

0.1

482 spp

314 spp

0.301

0.136

1

518 spp

318 spp

0.0265

0.0401

An antithetic frame costs 50 to 75% more: it solves for an antithetic vertex and evaluates its path for every sampled vertex. With the short wavelength, most of the indirect light cancels, and naive sampling shows only noise; antithetic sampling, with fewer samples, already shows the rings and stripes of the reference, at a 7 times lower error. The gain shrinks as the wavelength grows: the antithetic path, half a wavelength longer or shorter, is farther from the sampled one and less similar to it, and the measurement no longer cancels much. At \(\lambda = 1\), comparable to the size of the box, naive sampling is better for the same time.

5. Show the images

The images are signed: a diverging colormap shows 0 in white, positive values in red and negative ones in blue, with the range of each row set by the reference.

fig, axes = plt.subplots(len(rows), 3, figsize=(9, 3.2 * len(rows)))
for row, (wavelength, images) in zip(axes, rows):
    limit = np.percentile(np.abs(images[-1][1]), 99)
    for ax, (label, image) in zip(row, images):
        ax.imshow(image, cmap="bwr", vmin=-limit, vmax=limit)
        ax.set_title(label, fontsize=10)
        ax.set_xticks([])
        ax.set_yticks([])
    row[0].set_ylabel(f"$\\lambda$ = {wavelength}", fontsize=12)
fig.tight_layout()
fig.savefig("cwtof_antithetic.png", dpi=100)

The full script: cwtof_antithetic.py. It takes about two minutes, most of it for the references.