Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve plotter output, introduce randomness #135

Merged
merged 4 commits into from
Jan 21, 2024
Merged
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
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