Skip to content

Instantly share code, notes, and snippets.

@sverhoeven
Created October 2, 2020 09:38
Show Gist options
  • Save sverhoeven/a9d209c6157dd02b90c4499b6b60e60c to your computer and use it in GitHub Desktop.
Save sverhoeven/a9d209c6157dd02b90c4499b6b60e60c to your computer and use it in GitHub Desktop.
run-cpp-on-web: vega
<html>
<head>
<script type="text/javascript" src="newtonraphson.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
</head>
<body>
<div id="plot"></div>
<script>
createModule().then(({NewtonRaphson}) => {
const initial_guess = -4;
const tolerance = 0.001;
const newtonraphson = new NewtonRaphson(tolerance);
newtonraphson.solve(initial_guess);
// newtonraphson.iterations is a vector object which not consumeable by Vega
// So convert Emscripten vector of objects to JavaScript array of objects
const iterations = new Array(
newtonraphson.iterations.size()
).fill().map(
(_, iteration) => {
return newtonraphson.iterations.get(iteration)
}
);
// Open console in DevTools (F12) to see iterations data as a JSON string
console.log(JSON.stringify(iterations, null, 2));
const spec = {
"$schema": "https://vega.github.io/schema/vega-lite/v4.json",
"width": 800,
"height": 600,
"title": {
"text": "Iterations",
"fontSize": 20,
"fontWeight": "normal"
},
"data": {
"values": iterations
},
"encoding": {
"x": {
"field": "index",
"type": "quantitative",
"title": "Iteration index",
"axis": {
"labelFontSize": 20,
"titleFontSize": 20,
"labelFontWeight": "lighter",
"tickMinStep": 1.0
}
},
"y": {
"field": "y",
"type": "quantitative",
"axis": {
"labelFontSize": 20,
"titleFontSize": 20,
"labelFontWeight": "lighter"
}
}
},
"mark": {
"type": "line",
"point": true,
// Enable tooltip so on mouseover it shows all data of that iteration
"tooltip": {"content": "data"}
},
// Enable zooming and panning
"selection": {"grid": {"type": "interval", "bind": "scales"}}
};
vegaEmbed(document.getElementById("plot"), spec);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment