Skip to content

Commit

Permalink
Improve plotter output, introduce randomness (#135)
Browse files Browse the repository at this point in the history
This improves the `sample` function central to Mafs' plotter.

### Bug fix: duplicate points, incorrect subdivision

First, it corrects a bug that was causing duplicate points to be
evaluated. For example, when sampling the domain [-16, 16] with sampling
depth 4, these points were being generated:

```
[-16,-15,-13,-12,-12,-11,-9,-8,-8,-7,-5,-4,-4,-3,-1,0,0,1,3,4,4,5,7,8,8,9,11,12,12,13,15,16]
```

Of course, duplicates make no sense here, and we would actually expect a
uniform distribution between -16 and 16. Also, we would expect depth _5_
to produce 32 segments (33 points), not depth 4. So that was fixed by,
thankfully, removing code.

### Randomness

Additionally, for quite some time, I have been wanting to introduce some
stable randomness to the sampling function, in a way that prevents the
function from changing with every render. I finally decided to research
that and introduce a pseudo-random hash function when evaluating the
midpoint of the domain. This also required the `midpoint` function in
`sample` to become a `lerp`, since we can no longer simply measure
against the midpoint to compute errors.
  • Loading branch information
stevenpetryk authored Jan 21, 2024
1 parent d7d0b50 commit 2a0fbde
Show file tree
Hide file tree
Showing 9 changed files with 71 additions and 37 deletions.
22 changes: 17 additions & 5 deletions docs/app/guides/display/plots/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -92,18 +92,30 @@ function Functions() {
<code>minSamplingDepth</code> and <code>maxSamplingDepth</code> props can be tuned.
Increasing <code>minSamplingDepth</code> can help when you want to ensure more subdivisions
and improve accuracy, and lowering <code>maxSamplingDepth</code> can help improve
performance. These two props should be tuned to meet your needs.
performance.
</p>

<p>
Here's an example of a common "stress test" function for plotters, sin(1/x). The top plot
has the default sampling depths, while the bottom has <code>minSamplingDepth</code>{" "}
increased to <code>15</code>. Neither approach is perfect, but the bottom render is
indistinguishable from a perfect plot.
Here's an example of a common "stress test" function for plotters, sin(1/x). This function
exhibits an infinite oscillation frequency as x approaches 0, requiring theoretically
infinite sampling to render perfectly.
</p>

<p>
The top plot has the default sampling depths, while the bottom has{" "}
<code>minSamplingDepth</code> increased to <code>16</code>. More samples still doesn't
render the function perfectly, but it's much closer (at the cost of performance: the bottom
plot has nearly 3 megabytes of SVG path data).
</p>

<CodeAndExample component={<SineStressTest />} source={SineStressTestSource} />

<p>
If you pan this example around, you may see a considerably slow framerate. Interestingly,
this slowness is happening in the browser code itself, not in JavaScript (and therefore not
in Mafs). It would seem that merely rendering large SVG paths is expensive.
</p>

<h3>Vector fields</h3>

<p>
Expand Down
4 changes: 2 additions & 2 deletions docs/components/guide-examples/plots/sine-stress-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ export default function SineStressTest() {
preserveAspectRatio={false}
>
<Coordinates.Cartesian />
<Plot.OfX y={(x) => fn(x) + 1.5} />
<Plot.OfX y={(x) => fn(x) + 1.5} weight={1} />
{/* prettier-ignore */}
<Plot.OfX y={(x) => fn(x) - 1.5} minSamplingDepth={15} />
<Plot.OfX y={(x) => fn(x) - 1.5} minSamplingDepth={16} weight={1} />
</Mafs>
)
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
23 changes: 23 additions & 0 deletions src/display/Plot/PlotUtils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { sample } from "./PlotUtils"

test("sample", () => {
const ts: number[] = []

sample<number>({
domain: [0, 8],
minDepth: 3,
maxDepth: 3,
error: () => Number.POSITIVE_INFINITY,
fn: (t) => t,
lerp: () => 0,
onPoint(t) {
ts.push(t)
},
threshold: 0,
})

// Since the sample function deliberately introduces randomness, we round to test.
const roundedTs = ts.map(Math.round)

expect(roundedTs).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8])
})
59 changes: 29 additions & 30 deletions src/display/Plot/PlotUtils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ interface SampleParams<P> {
fn: (t: number) => P
/** A function that computes the error between a real sample function output and a midpoint output */
error: (real: P, estimate: P) => number
/** A function that computes the midpoint of two sample function outputs */
midpoint: (p1: P, p2: P) => P
/** A function that computes the lerp of two sample function outputs, for purpose of comparing to the function's real output */
lerp: (p1: P, p2: P, t: number) => P
/** A function that is called whenever a point should be part of the sample */
onPoint: (t: number, p: P) => void
/** The domain to sample */
Expand All @@ -19,64 +19,63 @@ interface SampleParams<P> {
threshold: number
}

/**
* Cheap psuedo-random hash function to consistently generate randomness when
* sampling functions. This return a value between 0.4 and 0.6.
*/
function cheapHash(min: number, max: number) {
const result = Math.sin(min * 12.9898 + max * 78.233) * 43758.5453
return 0.4 + 0.2 * (result - Math.floor(result))
}

/**
* A relatively generic internal function which, given a function, domain, and
* an error function, will recursively subdivide the domain until sampling said
* function at each point in the domain yields an error less than the supplied
* threshold. Importantly, this makes no assumptions about the return type of
* the sampled function.
*/
function sample<SampledReturnType>({
export function sample<SampledReturnType>({
domain,
minDepth,
maxDepth,
threshold,
fn,
error,
onPoint,
midpoint,
lerp,
}: SampleParams<SampledReturnType>) {
const [min, max] = domain

function subdivide(
min: number,
max: number,
pushLeft: boolean,
pushRight: boolean,
depth: number,
pMin: SampledReturnType,
pMax: SampledReturnType,
) {
const t = 0.5
const t = cheapHash(min, max)
const mid = min + (max - min) * t
const pMid = fn(mid)

if (depth < minDepth) {
subdivide(min, mid, true, false, depth + 1, pMin, pMid)
subdivide(mid, max, false, true, depth + 1, pMid, pMax)
return
function deepen() {
subdivide(min, mid, depth + 1, pMin, pMid)
onPoint(mid, pMid)
subdivide(mid, max, depth + 1, pMid, pMax)
}

if (depth < maxDepth) {
const fnMidpoint = midpoint(pMin, pMax)
if (depth < minDepth) {
deepen()
} else if (depth < maxDepth) {
const fnMidpoint = lerp(pMin, pMax, t)
const e = error(pMid, fnMidpoint)
if (e > threshold) {
subdivide(min, mid, true, false, depth + 1, pMin, pMid)
subdivide(mid, max, false, true, depth + 1, pMid, pMax)
return
}
}

if (pushLeft) {
onPoint(min, pMin)
}
onPoint(mid, pMid)
if (pushRight) {
onPoint(max, pMax)
if (e > threshold) deepen()
}
}

subdivide(min, max, true, true, 0, fn(min), fn(max))
onPoint(min, fn(min))
subdivide(min, max, 0, fn(min), fn(max))
onPoint(max, fn(max))
}

export function sampleParametric(
Expand All @@ -96,7 +95,7 @@ export function sampleParametric(
result += `${x} ${y} L `
}
},
midpoint: (p1, p2) => vec.midpoint(p1, p2),
lerp: (p1, p2, t) => vec.lerp(p1, p2, t),
domain,
minDepth,
maxDepth,
Expand Down Expand Up @@ -141,8 +140,8 @@ export function sampleInequality(
error: ([realLower, realUpper], [estLower, estUpper]) => {
return Math.max(vec.squareDist(realLower, estLower), vec.squareDist(realUpper, estUpper))
},
midpoint: ([aLower, aUpper], [bLower, bUpper]) => {
return [vec.midpoint(aLower, bLower), vec.midpoint(aUpper, bUpper)]
lerp: ([aLower, aUpper], [bLower, bUpper], t) => {
return [vec.lerp(aLower, bLower, t), vec.lerp(aUpper, bUpper, t)]
},
onPoint: (x, [[, lower], [, upper]]) => {
// TODO: these inequality operators should reflect the props, perhaps
Expand Down

1 comment on commit 2a0fbde

@vercel
Copy link

@vercel vercel bot commented on 2a0fbde Jan 21, 2024

Choose a reason for hiding this comment

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

Please sign in to comment.