11 |
12 |
--------------------------------------------------------------------------------
/src/viz/path_client/index.less:
--------------------------------------------------------------------------------
1 | * {
2 | box-sizing: border-box;
3 | margin: 0;
4 | padding: 0;
5 | }
6 |
7 | html, body {
8 | width: 100%;
9 | height: 100%;
10 | font-family: sans-serif;
11 | font-weight: lighter;
12 | font-size: 14px;
13 | }
14 |
15 | @import "./app/index";
16 |
--------------------------------------------------------------------------------
/src/viz/gulp/utils/stream_readableFromString.js:
--------------------------------------------------------------------------------
1 | import { default as stream } from 'stream'
2 |
3 | export default function(string) {
4 | var readable = new stream.Readable();
5 | readable._read = function noop() {}
6 | readable.push(string)
7 | readable.push(null)
8 | return readable
9 | }
10 |
--------------------------------------------------------------------------------
/src/viz/path/chart/resize.js:
--------------------------------------------------------------------------------
1 | import { default as Component } from '.'
2 |
3 | Component.prototype.resize = function() {
4 | this.updateScalesGeometry()
5 | this.updateGenerators()
6 | this.updateSkeletonGeometry()
7 | this.updateAxes()
8 | this.updateCurvesGeometry()
9 | this.updateSensors()
10 | }
11 |
--------------------------------------------------------------------------------
/src/viz/path/app/index.less:
--------------------------------------------------------------------------------
1 | .app {
2 | width: 100%;
3 | height: 100%;
4 | display: flex;
5 |
6 | #Chart {
7 | flex: 1;
8 | }
9 | #Controls {
10 | flex: 0 0 275px;
11 | margin-right: 0.5em;
12 | }
13 | }
14 |
15 | @import "../chart/index";
16 | @import "../controls/index";
17 |
--------------------------------------------------------------------------------
/src/viz/path_client/chart/stats.js:
--------------------------------------------------------------------------------
1 | import { default as Component } from '.'
2 | import { default as Stats } from 'stats.js'
3 |
4 | Component.prototype.initStats = function() {
5 | this.stats = new Stats()
6 | this.stats.showPanel(1) // 0: fps, 1: ms, 2: mb, 3+: custom
7 | document.body.appendChild( this.stats.dom )
8 | }
9 |
--------------------------------------------------------------------------------
/src/viz/path_client/app/index.less:
--------------------------------------------------------------------------------
1 | .app {
2 | width: 100%;
3 | height: 100%;
4 | display: flex;
5 |
6 | #Chart {
7 | flex: 1;
8 | }
9 | #Controls {
10 | flex: 0 0 275px;
11 | margin-right: 0.5em;
12 | }
13 | }
14 |
15 | @import "../chart/index";
16 | @import "../controls/index";
17 |
--------------------------------------------------------------------------------
/src/viz/path_client/chart/index.less:
--------------------------------------------------------------------------------
1 | .Chart {
2 | width: 100%;
3 | height: 100%;
4 | padding: 0.5em;
5 | font-size: 12px;
6 |
7 | svg {
8 | width: 100%;
9 | height: 100%;
10 |
11 | path {
12 | fill: none;
13 | // stroke: black;
14 | }
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/viz/path/app/skeleton.js:
--------------------------------------------------------------------------------
1 | import { default as d3 } from 'd3'
2 | import { default as App } from '.'
3 |
4 | App.prototype.setSkeleton = function() {
5 | let appdiv = d3.select(this.options.container).append('div').attr('class', 'app')
6 | appdiv.append('div').attr('id', 'Chart')
7 | appdiv.append('div').attr('id', 'Controls')
8 | }
9 |
--------------------------------------------------------------------------------
/src/viz/path/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Path - Bench
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/src/viz/gulp/tasks/data.js:
--------------------------------------------------------------------------------
1 | import path from 'path'
2 | import { default as gulp } from 'gulp'
3 | import { default as gutil } from 'gulp-util'
4 | import { default as config } from '../config'
5 |
6 | gulp.task('data', () => {
7 | return gulp.src(path.resolve(config.dataDir, 'path.json'))
8 | .pipe(gulp.dest(config.buildDataDir).on('error', gutil.log))
9 | })
10 |
--------------------------------------------------------------------------------
/src/viz/gulp/tasks/build.js:
--------------------------------------------------------------------------------
1 | import { default as gulp } from 'gulp'
2 | import { default as _ } from 'lodash'
3 | import { default as config } from '../config'
4 |
5 | gulp.task('build',
6 | _.chain(config.vizDirNames)
7 | .map(dirName =>
8 | _.map(['logic', 'style', 'html'], taskType => `${taskType}.${dirName}`)
9 | )
10 | .flatten()
11 | .value()
12 | )
13 |
--------------------------------------------------------------------------------
/src/viz/path_client/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Path - Client
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/src/viz/path_client/chart/events.js:
--------------------------------------------------------------------------------
1 | import { default as _ } from 'lodash'
2 | import { default as d3 } from 'd3'
3 | import { Observable } from 'rxjs-es'
4 | import { default as Component } from '.'
5 |
6 | Component.prototype.setEvents = function() {
7 | Observable.fromEvent(window, 'resize')
8 | .subscribe(() => {
9 | this.geometry.dirty = true
10 | this.resize()
11 | })
12 | }
13 |
--------------------------------------------------------------------------------
/src/viz/path_client/chart/scales.js:
--------------------------------------------------------------------------------
1 | import { default as d3 } from 'd3'
2 | import { default as Component } from '.'
3 |
4 | Component.prototype.initScales = function() {
5 | this.scales = {
6 | x: d3.scaleLinear().domain([0, 1]),
7 | y: d3.scaleLinear().domain([0, 1])
8 | }
9 | }
10 |
11 | Component.prototype.updateScalesGeometry = function() {
12 | this.scales.x.range([0, this.geometry.radius])
13 | this.scales.y.range([0, this.geometry.radius])
14 | }
15 |
--------------------------------------------------------------------------------
/src/viz/gulp/tasks/html.js:
--------------------------------------------------------------------------------
1 | import path from 'path'
2 | import { default as gulp } from 'gulp'
3 | import { default as gutil } from 'gulp-util'
4 | import { default as config } from '../config'
5 |
6 | config.vizDirNames.forEach(vizDir => {
7 | gulp.task(`html.${vizDir}`, () => {
8 | return gulp.src(`./${vizDir}/index.html`)
9 | .pipe(
10 | gulp.dest(path.resolve(config.buildDir, vizDir))
11 | .on('error', gutil.log)
12 | )
13 | })
14 | })
15 |
--------------------------------------------------------------------------------
/src/viz/gulp/tasks/vendor.js:
--------------------------------------------------------------------------------
1 | import path from 'path'
2 | import { default as gulp } from 'gulp'
3 | import { default as gutil } from 'gulp-util'
4 | import { default as config } from '../config'
5 |
6 | gulp.task('vendor', () => {
7 | return gulp.src([
8 | path.resolve(config.rootDir, 'node_modules/d3/build/d3.js'),
9 | path.resolve(config.rootDir, 'node_modules/lodash/lodash.js')
10 | ])
11 | .pipe(gulp.dest(config.buildVendorDir).on('error', gutil.log))
12 | })
13 |
--------------------------------------------------------------------------------
/src/viz/utils/element_get_geometry.js:
--------------------------------------------------------------------------------
1 | import { default as _ } from 'lodash'
2 |
3 | export default function(elem, additionalProps) {
4 | let inspectedProps = ['width', 'height']
5 | if (!_.isUndefined(additionalProps)) {
6 | inspectedProps = inspectedProps.concat(additionalProps)
7 | }
8 | return _.chain(getComputedStyle(elem))
9 | .pick(inspectedProps)
10 | .mapValues(function(pxValue) { return parseFloat(pxValue, 10); })
11 | .value()
12 | }
13 |
--------------------------------------------------------------------------------
/src/viz/path_client/chart/curve.js:
--------------------------------------------------------------------------------
1 | import { default as Component } from '.'
2 |
3 | Component.prototype.initCurve = function() {
4 | this.path = this.g.append('path')
5 | }
6 |
7 | Component.prototype.updateCurve = function() {
8 | if (this.stats) {this.stats.begin()}
9 | this.path.attr('d', this.line(this.data) + 'Z')
10 | if (this.stats) {this.stats.end()}
11 | }
12 |
13 | Component.prototype.updateCurveStyle = function() {
14 | this.path.attr('stroke', this.implColor(this.sharedState.impl))
15 | }
16 |
--------------------------------------------------------------------------------
/src/viz/gulp/config.js:
--------------------------------------------------------------------------------
1 | import path from 'path'
2 | import findup from 'findup'
3 |
4 | const rootDir = findup.sync('.', 'package.json')
5 | const buildDir = path.resolve(rootDir, 'build/')
6 |
7 | export default {
8 | rootDir: rootDir,
9 | dataDir: path.resolve(rootDir, 'data/'),
10 | buildDir: buildDir,
11 | buildDataDir: path.resolve(buildDir, 'data/'),
12 | buildVendorDir: path.resolve(buildDir, 'vendor/'),
13 | vizDir: path.resolve(rootDir, 'src/viz/'),
14 | vizDirNames: ['path', 'path_client']
15 | }
16 |
--------------------------------------------------------------------------------
/src/implementations/utils/round.js:
--------------------------------------------------------------------------------
1 | // https://github.com/d3/d3-format/issues/32
2 | export function round(x, n) {
3 | return n == null ? Math.round(x) : Math.round(x * (n = Math.pow(10, n))) / n;
4 | }
5 |
6 | // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round#PHP-Like_rounding_Method
7 | export function roundMDN(x, n) {
8 | var factor = Math.pow(10, n);
9 | var tempNumber = x * factor;
10 | var roundedTempNumber = Math.round(tempNumber);
11 | return roundedTempNumber / factor;
12 | }
13 |
--------------------------------------------------------------------------------
/rollup.config.js:
--------------------------------------------------------------------------------
1 | import { default as nodeResolve } from 'rollup-plugin-node-resolve'
2 | import { default as commonjs } from 'rollup-plugin-commonjs'
3 | import buble from 'rollup-plugin-buble'
4 |
5 | export default {
6 | entry: 'src/implementations/index.js',
7 | dest: 'build/bundle.js',
8 | format: 'umd',
9 | moduleName: 'implementations',
10 | plugins: [
11 | nodeResolve({
12 | module: true,
13 | jsnext: true,
14 | main: true,
15 | browser: true
16 | }),
17 | commonjs(),
18 | buble()
19 | ]
20 | }
21 |
--------------------------------------------------------------------------------
/src/viz/path/chart/colors.js:
--------------------------------------------------------------------------------
1 | import { default as d3 } from 'd3'
2 | import { default as _ } from 'lodash'
3 | import { default as Component } from '.'
4 |
5 | Object.defineProperty(Component.prototype, 'implColor', {
6 | get: function () {
7 | if(_.isUndefined(this._implColor)) {
8 | let hueScale =
9 | d3.scalePoint()
10 | .domain(this.data.allImplementations)
11 | .range([0, 300])
12 | this._implColor = key => d3.hsl(hueScale(key), 0.5, 0.5)
13 | }
14 | return this._implColor
15 | }
16 | })
17 |
--------------------------------------------------------------------------------
/src/viz/path_client/controls/colors.js:
--------------------------------------------------------------------------------
1 | import { default as d3 } from 'd3'
2 | import { default as _ } from 'lodash'
3 | import { default as Component } from '.'
4 |
5 | Object.defineProperty(Component.prototype, 'implColor', {
6 | get: function () {
7 | if(_.isUndefined(this._implColor)) {
8 | let hueScale =
9 | d3.scalePoint()
10 | .domain(this.options.data.impl)
11 | .range([0, 300])
12 | this._implColor = key => d3.hsl(hueScale(key), 0.5, 0.5)
13 | }
14 | return this._implColor
15 | }
16 | })
17 |
--------------------------------------------------------------------------------
/src/viz/path_client/chart/colors.js:
--------------------------------------------------------------------------------
1 | import { default as d3 } from 'd3'
2 | import { default as _ } from 'lodash'
3 | import { default as Component } from '.'
4 |
5 | Object.defineProperty(Component.prototype, 'implColor', {
6 | get: function () {
7 | if(_.isUndefined(this._implColor)) {
8 | let hueScale =
9 | d3.scalePoint()
10 | .domain(this.options.allImplementations)
11 | .range([0, 300])
12 | this._implColor = key => d3.hsl(hueScale(key), 0.5, 0.5)
13 | }
14 | return this._implColor
15 | }
16 | })
17 |
--------------------------------------------------------------------------------
/src/viz/path/chart/skeleton.js:
--------------------------------------------------------------------------------
1 | import { default as Component } from '.'
2 |
3 | Component.prototype.initSkeleton = function() {
4 | this.container =
5 | this.options.container.append('div')
6 | .attr('class', this.name)
7 | this.svg = this.container.append('svg')
8 | this.g = this.svg.append('g')
9 | }
10 |
11 | Component.prototype.updateSkeletonGeometry = function() {
12 | this.svg
13 | .attr('width', this.geometry.width)
14 | .attr('height', this.geometry.height)
15 |
16 | this.g
17 | .attr('transform', `translate(${this.geometry.origin})`)
18 | }
19 |
--------------------------------------------------------------------------------
/src/viz/path/chart/events.js:
--------------------------------------------------------------------------------
1 | import { default as _ } from 'lodash'
2 | import { default as d3 } from 'd3'
3 | import { Observable } from 'rxjs-es'
4 | import { default as Component } from '.'
5 |
6 | Component.prototype.setEvents = function() {
7 | // internal events
8 | this.dispatch =
9 | d3.dispatch('focus_changed')
10 | .on('focus_changed', obj => {this.focusDots(obj)})
11 |
12 | // window events
13 | Observable.fromEvent(window, 'resize')
14 | // .debounceTime(20)
15 | .subscribe(() => {
16 | this.geometry.dirty = true
17 | this.resize()
18 | })
19 | }
20 |
--------------------------------------------------------------------------------
/src/viz/path/chart/scales.js:
--------------------------------------------------------------------------------
1 | import { default as d3 } from 'd3'
2 | import { default as Component } from '.'
3 |
4 | Component.prototype.initScales = function() {
5 | this.scales = {
6 | t: d3.scaleLog(),
7 | m: d3.scaleLog()
8 | }
9 | }
10 |
11 | Component.prototype.updateScalesData = function() {
12 | this.scales.t.domain(this.data.tExtent)
13 | this.scales.m.domain(this.data.mExtent)
14 | }
15 |
16 | Component.prototype.updateScalesGeometry = function() {
17 | this.scales.t.range([0, this.geometry.innerWidth])
18 | this.scales.m.range([this.geometry.innerHeight, 0])
19 | }
20 |
--------------------------------------------------------------------------------
/src/viz/path_client/chart/skeleton.js:
--------------------------------------------------------------------------------
1 | import { default as Component } from '.'
2 |
3 | Component.prototype.initSkeleton = function() {
4 | this.container =
5 | this.options.container.append('div')
6 | .attr('class', this.name)
7 | this.svg = this.container.append('svg')
8 | this.g = this.svg.append('g')
9 | }
10 |
11 | Component.prototype.updateSkeletonGeometry = function() {
12 | this.svg
13 | .attr('width', this.geometry.width)
14 | .attr('height', this.geometry.height)
15 |
16 | this.g
17 | .attr('transform', `translate(${this.geometry.origin})`)
18 | }
19 |
--------------------------------------------------------------------------------
/src/viz/path_client/chart/index.js:
--------------------------------------------------------------------------------
1 | export default Component
2 | import './colors'
3 | import './curve'
4 | import './events'
5 | import './geometry'
6 | import './resize'
7 | import './scales'
8 | import './stats'
9 | import './skeleton'
10 | import './update'
11 |
12 | function Component(options) {
13 | this.name = 'Chart'
14 | this.options = options
15 | this.initSkeleton()
16 | this.updateSkeletonGeometry()
17 | this.initScales()
18 | this.updateScalesGeometry()
19 | this.initCurve()
20 | this.initStats()
21 | this.startAnimation()
22 | this.subscribeToState()
23 | this.setEvents()
24 | }
25 |
--------------------------------------------------------------------------------
/src/viz/gulp/tasks/style.js:
--------------------------------------------------------------------------------
1 | import path from 'path'
2 | import gulp from 'gulp'
3 | import gutil from 'gulp-util'
4 | import less from 'gulp-less'
5 | import { default as browserSync } from 'browser-sync'
6 | import config from '../config'
7 |
8 | config.vizDirNames.forEach(dirName => {
9 | gulp.task(`style.${dirName}`, () => {
10 | return gulp.src(`./${dirName}/index.less`)
11 | .pipe(less().on('error', gutil.log))
12 | .pipe(
13 | gulp.dest(path.resolve(config.buildDir, dirName))
14 | .on('error', gutil.log)
15 | )
16 | .pipe(browserSync.stream())
17 | })
18 | })
19 |
--------------------------------------------------------------------------------
/src/viz/path/chart/index.js:
--------------------------------------------------------------------------------
1 | export default Component
2 | import './axes'
3 | import './colors'
4 | import './curves'
5 | import './data'
6 | import './events'
7 | import './generators'
8 | import './geometry'
9 | import './resize'
10 | import './scales'
11 | import './skeleton'
12 | import './sensors'
13 |
14 | function Component(options) {
15 | this.name = 'Chart'
16 | this.options = options
17 |
18 | this.initSkeleton()
19 | this.updateSkeletonGeometry()
20 |
21 | this.initScales()
22 | this.updateScalesGeometry()
23 |
24 | this.initGenerators()
25 | this.initAxes()
26 | this.initSensors()
27 | this.initCurves()
28 |
29 | this.connectData()
30 | this.setEvents()
31 | }
32 |
--------------------------------------------------------------------------------
/src/viz/path/controls/colors.js:
--------------------------------------------------------------------------------
1 | import { default as d3 } from 'd3'
2 | import { default as _ } from 'lodash'
3 | import { default as Component } from '.'
4 |
5 | Object.defineProperty(Component.prototype, 'implColor', {
6 | get: function () {
7 | if(_.isUndefined(this._implColor)) {
8 | let implementations =
9 | _.chain(this.options.data)
10 | .groupBy(obj => obj.impl)
11 | .keys()
12 | .value()
13 |
14 | let hueScale =
15 | d3.scalePoint()
16 | .domain(implementations)
17 | .range([0, 300])
18 | this._implColor = key => d3.hsl(hueScale(key), 0.5, 0.5)
19 | }
20 | return this._implColor
21 | }
22 | })
23 |
--------------------------------------------------------------------------------
/src/viz/path/chart/sensors.js:
--------------------------------------------------------------------------------
1 | import { default as Component } from '.'
2 |
3 | Component.prototype.initSensors = function() {
4 | this.sensors = this.g.append('g').attr('class', 'sensors')
5 | }
6 |
7 | Component.prototype.updateSensors = function() {
8 | var polygons =
9 | this.generators.voronoi.polygons(this.data.uniquePoints)
10 |
11 | var sensor =
12 | this.sensors.selectAll('.sensor').data(polygons)
13 |
14 | sensor.exit().remove()
15 | sensor.enter()
16 | .append('path')
17 | .attr('class', 'sensor')
18 | .on('mouseover', d => { this.dispatch.call('focus_changed', this, d.data) })
19 | .on('mouseout', () => { this.dispatch.call('focus_changed', this, null) })
20 | .merge(sensor)
21 | .attr('d', d => 'M' + d.join('L') + 'Z')
22 | }
23 |
--------------------------------------------------------------------------------
/src/viz/gulp/tasks/deploy.js:
--------------------------------------------------------------------------------
1 | import path from 'path'
2 | import gulp from 'gulp'
3 | import gutil from 'gulp-util'
4 | import { default as runSequence } from 'run-sequence'
5 | import { default as ghPages } from 'gulp-gh-pages'
6 | import { default as options } from '../options'
7 | import { default as config } from '../config'
8 |
9 | gulp.task('commitToGhPages', () => {
10 | var opts = {cacheDir: path.resolve(config.rootDir, '.gh_pages_cache')}
11 | if (options.m) { opts.message = options.m }
12 |
13 | return gulp.src(path.resolve(config.buildDir, '**/*')).pipe( ghPages(opts) )
14 | })
15 |
16 | gulp.task('copyGhPagesIndex', () => {
17 | return gulp.src(`./index.html`)
18 | .pipe(gulp.dest(config.buildDir).on('error', gutil.log))
19 | })
20 |
21 | gulp.task('deploy', () => {
22 | runSequence(['data', 'vendor', 'build', 'copyGhPagesIndex'], 'commitToGhPages')
23 | })
24 |
--------------------------------------------------------------------------------
/src/implementations/shape/curve/linear.js:
--------------------------------------------------------------------------------
1 | function Linear(context) {
2 | this._context = context;
3 | }
4 |
5 | Linear.prototype = {
6 | areaStart: function() {
7 | this._line = 0;
8 | },
9 | areaEnd: function() {
10 | this._line = NaN;
11 | },
12 | lineStart: function() {
13 | this._point = 0;
14 | },
15 | lineEnd: function() {
16 | if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath();
17 | this._line = 1 - this._line;
18 | },
19 | point: function(x, y) {
20 | x = +x, y = +y;
21 | switch (this._point) {
22 | case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break;
23 | case 1: this._point = 2; // proceed
24 | default: this._context.lineTo(x, y); break;
25 | }
26 | }
27 | };
28 |
29 | export default function(context) {
30 | return new Linear(context);
31 | }
32 |
--------------------------------------------------------------------------------
/src/viz/path/chart/generators.js:
--------------------------------------------------------------------------------
1 | import { default as d3 } from 'd3'
2 | import { default as Component } from '.'
3 |
4 | Component.prototype.initGenerators = function() {
5 | this.generators = {
6 | axes: {
7 | t: d3.axisBottom(),
8 | m: d3.axisLeft()
9 | },
10 | line: d3.line()
11 | .curve(d3.curveNatural)
12 | .x(d => this.scales.t(d.duration))
13 | .y(d => this.scales.m(d.heap)),
14 | voronoi: d3.voronoi()
15 | .x(d => this.scales.t(d.duration))
16 | .y(d => this.scales.m(d.heap))
17 | }
18 | }
19 |
20 | Component.prototype.updateGenerators = function() {
21 | this.generators.axes.t
22 | .scale(this.scales.t)
23 | .tickSize(-this.geometry.innerHeight)
24 |
25 | this.generators.axes.m
26 | .scale(this.scales.m)
27 | .tickSize(-this.geometry.innerWidth)
28 |
29 | this.generators.voronoi.extent(this.geometry.extent)
30 | }
31 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "d3-benchmarks",
3 | "version": "0.0.0",
4 | "main": "src/index.js",
5 | "scripts": {
6 | "build": "rollup -c",
7 | "path": "node --expose-gc src/bench/path.js",
8 | "round": "node src/bench/round.js"
9 | },
10 | "author": "Luca Bonavita (mindrones.com)",
11 | "dependencies": {
12 | "benchmark": "^2.1.2",
13 | "d3": "^4.4.0",
14 | "d3-path": "^1.0.3",
15 | "escodegen": "^1.8.1",
16 | "esprima": "^3.1.2",
17 | "lodash": "^4.17.2",
18 | "microtime": "^2.1.2",
19 | "rxjs-es": "^5.0.0-beta.12",
20 | "stats.js": "^0.17.0"
21 | },
22 | "devDependencies": {
23 | "babel-core": "^6.21.0",
24 | "babel-preset-es2015": "^6.18.0",
25 | "babel-register": "^6.18.0",
26 | "browser-sync": "^2.18.5",
27 | "findup": "^0.1.5",
28 | "gulp": "^3.9.1",
29 | "gulp-gh-pages": "^0.5.4",
30 | "gulp-less": "^3.3.0",
31 | "gulp-util": "^3.0.8",
32 | "rollup": "^0.36.4",
33 | "rollup-plugin-buble": "^0.14.0",
34 | "rollup-plugin-commonjs": "^6.0.1",
35 | "rollup-plugin-node-resolve": "^2.0.0",
36 | "run-sequence": "^1.2.2",
37 | "vinyl-source-stream": "^1.1.0"
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/data/rounding.txt:
--------------------------------------------------------------------------------
1 | round.0 x 64,605,524 ops/sec
2 | round.5 x 62,588,594 ops/sec
3 | round.10 x 60,480,488 ops/sec
4 | round.15 x 63,932,299 ops/sec
5 | round.CoerceNumber.0 x 65,084,597 ops/sec
6 | round.CoerceNumber.5 x 58,614,775 ops/sec
7 | round.CoerceNumber.10 x 63,046,349 ops/sec
8 | round.CoerceNumber.15 x 63,467,761 ops/sec
9 | round.CoerceString.0 x 65,427,016 ops/sec
10 | round.CoerceString.5 x 63,492,123 ops/sec
11 | round.CoerceString.10 x 63,984,645 ops/sec
12 | round.CoerceString.15 x 63,868,512 ops/sec
13 | roundMDN.0 x 68,948,430 ops/sec
14 | roundMDN.5 x 69,194,930 ops/sec
15 | roundMDN.10 x 70,055,618 ops/sec
16 | roundMDN.15 x 69,475,818 ops/sec
17 | roundMDN.CoerceNumber.0 x 68,635,687 ops/sec
18 | roundMDN.CoerceNumber.5 x 71,012,138 ops/sec
19 | roundMDN.CoerceNumber.10 x 72,010,247 ops/sec
20 | roundMDN.CoerceNumber.15 x 71,583,248 ops/sec
21 | roundMDN.CoerceString.0 x 71,171,308 ops/sec
22 | roundMDN.CoerceString.5 x 68,070,564 ops/sec
23 | roundMDN.CoerceString.10 x 68,548,870 ops/sec
24 | roundMDN.CoerceString.15 x 69,196,418 ops/sec
25 | fixed.0 x 2,882,530 ops/sec
26 | fixed.5 x 2,654,246 ops/sec
27 | fixed.10 x 2,614,480 ops/sec
28 | fixed.15 x 2,384,442 ops/sec
29 | fixed.CoerceNumber.0 x 2,987,986 ops/sec
30 | fixed.CoerceNumber.5 x 2,737,227 ops/sec
31 | fixed.CoerceNumber.10 x 2,668,296 ops/sec
32 | fixed.CoerceNumber.15 x 2,517,428 ops/sec
33 | fixed.CoerceString.0 x 3,021,695 ops/sec
34 | fixed.CoerceString.5 x 2,724,436 ops/sec
35 | fixed.CoerceString.10 x 2,662,986 ops/sec
36 | fixed.CoerceString.15 x 2,501,564 ops/sec
37 |
--------------------------------------------------------------------------------
/src/viz/gulp/tasks/serve.js:
--------------------------------------------------------------------------------
1 | import path from 'path'
2 | import { default as gulp } from 'gulp'
3 | import { default as runSequence } from 'run-sequence'
4 | import { default as browserSync } from 'browser-sync'
5 | import { default as config } from '../config'
6 |
7 | gulp.task('serve', () => {
8 | browserSync.init({
9 | server: {baseDir: config.buildDir},
10 | port: 8001,
11 | open: false,
12 | reloadOnRestart: true,
13 | notify: false,
14 | ghostMode: false
15 | })
16 |
17 | gulp.watch([
18 | './path/**/*.js',
19 | './path_client/**/*.js'
20 | ], event => {
21 | let dirName = path.relative(config.vizDir, event.path).split(path.sep)[0]
22 | console.log(dirName)
23 |
24 | runSequence(`logic.${dirName}`, browserSync.reload)
25 | })
26 | gulp.watch([
27 | './path/*.less',
28 | './path/**/*.less',
29 | './path_client/*.less',
30 | './path_client/**/*.less'
31 | ], event => {
32 | let dirName = path.relative(config.vizDir, event.path).split(path.sep)[0]
33 | runSequence(`style.${dirName}`)
34 | })
35 | gulp.watch([
36 | './path/**/*.html',
37 | './path_client/**/*.html'
38 | ], event => {
39 | let dirName = path.relative(config.vizDir, event.path).split(path.sep)[0]
40 | runSequence(`html.${dirName}`, browserSync.reload)
41 | })
42 | gulp.watch(path.resolve(config.dataDir, '**/*.json'), () => {
43 | runSequence('data', browserSync.reload)
44 | })
45 | })
46 |
--------------------------------------------------------------------------------
/src/viz/path/chart/data.js:
--------------------------------------------------------------------------------
1 | import { default as _ } from 'lodash'
2 | import { default as d3 } from 'd3'
3 | import { default as Component } from '.'
4 |
5 | Component.prototype.connectData = function() {
6 | this.options.data$
7 | .map(input => {
8 | let data = {
9 | tExtent: d3.extent(input.items, obj => obj.duration),
10 | mExtent: d3.extent(input.items, obj => obj.heap)
11 | }
12 | data.curves =
13 | _.chain(input.items)
14 | .groupBy(obj => `${obj.impl.split('.').slice(1).join('.')}(${obj.digits}).${obj.command}`)
15 | .map((points, id) => ({
16 | id: id.replace(/null/g, ''),
17 | domID: id.replace(/[().]/g, '_'),
18 | impl: points[0].impl,
19 | points: points
20 | }))
21 | .value()
22 | data.points =
23 | _.map(input.items, obj => _.assign(obj, {
24 | id: `${obj.impl}|${obj.digits}|${obj.command}|${obj.calls}`,
25 | impl: obj.impl
26 | }))
27 | data.uniquePoints = _.uniqWith(data.points, (a, b) =>
28 | _.isEqual(
29 | _.pick(a, 'heap', 'duration'),
30 | _.pick(b, 'heap', 'duration')
31 | )
32 | )
33 | data.allImplementations = input.allImplementations
34 | return data
35 | })
36 | .subscribe(data => {
37 | this.data = data
38 | this.updateScalesData()
39 | this.updateGenerators()
40 | this.updateAxes()
41 | this.updateSensors()
42 | this.updateCurves()
43 | this.updateCurvesGeometry()
44 | })
45 | }
46 |
--------------------------------------------------------------------------------
/src/viz/gulp/tasks/logic.js:
--------------------------------------------------------------------------------
1 | import path from 'path'
2 | import gulp from 'gulp'
3 | import gutil from 'gulp-util'
4 | import { rollup } from 'rollup'
5 | import nodeResolve from 'rollup-plugin-node-resolve'
6 | import commonjs from 'rollup-plugin-commonjs'
7 | import buble from 'rollup-plugin-buble'
8 | import source from 'vinyl-source-stream'
9 | import readableFromString from '../utils/stream_readableFromString'
10 | import config from '../config'
11 |
12 | config.vizDirNames.forEach(dirName => {
13 | gulp.task(`logic.${dirName}`, () => {
14 | return rollup({
15 | entry: `./${dirName}/index.js`,
16 | external: ['d3', 'lodash', 'implementations'],
17 | plugins: [
18 | nodeResolve({
19 | module: true,
20 | jsnext: true,
21 | main: true,
22 | browser: true
23 | }),
24 | commonjs(),
25 | buble()
26 | ],
27 | }).then(bundle =>
28 | readableFromString(
29 | bundle.generate({
30 | format: 'iife',
31 | moduleName: 'index',
32 | globals: {
33 | d3: 'd3',
34 | lodash: '_'
35 | },
36 | banner: '/* https://github.com/mindrones/d3-benchmarks */',
37 | }).code
38 | )
39 | .pipe(source('index.js'))
40 | .pipe(
41 | gulp.dest(path.resolve(config.buildDir, dirName))
42 | .on('error', gutil.log)
43 | )
44 | )
45 | .catch(err => { console.log(err) })
46 | })
47 | })
48 |
--------------------------------------------------------------------------------
/src/implementations/shape/line.js:
--------------------------------------------------------------------------------
1 | // import {path} from "d3-path";
2 | import {path, pathRound} from "../path/withFormat";
3 | import constant from "./constant";
4 | import curveLinear from "./curve/linear";
5 | import {x as pointX, y as pointY} from "./point";
6 |
7 | export default function() {
8 | var x = pointX,
9 | y = pointY,
10 | defined = constant(true),
11 | context = null,
12 | curve = curveLinear,
13 | output = null,
14 | precision = null;
15 |
16 | function line(data) {
17 | var i,
18 | n = data.length,
19 | d,
20 | defined0 = false,
21 | buffer;
22 |
23 | if (context == null) output = curve(buffer = precision === null ? path() : pathRound(precision));
24 |
25 | for (i = 0; i <= n; ++i) {
26 | if (!(i < n && defined(d = data[i], i, data)) === defined0) {
27 | if (defined0 = !defined0) output.lineStart();
28 | else output.lineEnd();
29 | }
30 | if (defined0) output.point(+x(d, i, data), +y(d, i, data));
31 | }
32 |
33 | if (buffer) return output = null, buffer + "" || null;
34 | }
35 |
36 | line.precision = function(_) {
37 | return arguments.length ? (precision = _, line) : precision;
38 | };
39 |
40 | line.x = function(_) {
41 | return arguments.length ? (x = typeof _ === "function" ? _ : constant(+_), line) : x;
42 | };
43 |
44 | line.y = function(_) {
45 | return arguments.length ? (y = typeof _ === "function" ? _ : constant(+_), line) : y;
46 | };
47 |
48 | line.defined = function(_) {
49 | return arguments.length ? (defined = typeof _ === "function" ? _ : constant(!!_), line) : defined;
50 | };
51 |
52 | line.curve = function(_) {
53 | return arguments.length ? (curve = _, context != null && (output = curve(context)), line) : curve;
54 | };
55 |
56 | line.context = function(_) {
57 | return arguments.length ? (_ == null ? context = output = null : output = curve(context = _), line) : context;
58 | };
59 |
60 | return line;
61 | }
62 |
--------------------------------------------------------------------------------
/src/viz/path/controls/index.less:
--------------------------------------------------------------------------------
1 | .Controls {
2 | width: 100%;
3 | height: 100%;
4 | padding: 0.25em;
5 | font-size: 12px;
6 | overflow: auto;
7 |
8 | .panel {
9 | padding: 0.5em;
10 | margin-top: 1em;
11 | border-radius: 0.4em;
12 | background-color: darken(white, 2%);
13 |
14 | .title {
15 | font-weight: bold;
16 | padding: 0.25em 0.5em;
17 | border-bottom: 1px solid grey;
18 | margin-bottom: 0.5em;
19 | color: lighten(black, 15%);
20 | }
21 |
22 | .row {
23 | padding: 0.25em 0;
24 |
25 | display: flex;
26 | align-items: center;
27 |
28 | .dot {
29 | flex: 0 0 0.75em;
30 | height: 0.75em;
31 | border-radius: 50%;
32 | margin: 0 0.5em;
33 | }
34 |
35 | .value {
36 | flex: 1;
37 | cursor: pointer;
38 | padding: 0.25em 0.5em;
39 | border-radius: 0.25em;
40 |
41 | &:hover {
42 | background-color: darken(white, 10%);
43 | }
44 | &.pinned {
45 | background-color: darken(white, 35%);
46 | color: white;
47 | }
48 | p {
49 | pointer-events: none;
50 | }
51 | }
52 | }
53 | }
54 |
55 | .legend {
56 | margin-top: 1em;
57 |
58 | display: flex;
59 | align-items: center;
60 |
61 | .dot {
62 | width: 2em;
63 | height: 2em;
64 |
65 | display: flex;
66 | align-items: center;
67 | justify-content: center;
68 | border: 1px solid red;
69 | border-radius: 50%;
70 | }
71 |
72 | .phrase {
73 | flex: 1;
74 | margin-left: 0.5em;
75 | }
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/src/viz/path_client/controls/index.less:
--------------------------------------------------------------------------------
1 | .Controls {
2 | width: 100%;
3 | height: 100%;
4 | padding: 0.25em;
5 | font-size: 12px;
6 | overflow: auto;
7 |
8 | .panel {
9 | padding: 0.5em;
10 | margin-top: 1em;
11 | border-radius: 0.4em;
12 | background-color: darken(white, 2%);
13 |
14 | .title {
15 | font-weight: bold;
16 | padding: 0.25em 0.5em;
17 | border-bottom: 1px solid grey;
18 | margin-bottom: 0.5em;
19 | color: lighten(black, 15%);
20 | }
21 |
22 | .row {
23 | padding: 0.25em 0;
24 |
25 | display: flex;
26 | align-items: center;
27 |
28 | .dot {
29 | flex: 0 0 0.75em;
30 | height: 0.75em;
31 | border-radius: 50%;
32 | margin: 0 0.5em;
33 | }
34 |
35 | .value {
36 | flex: 1;
37 | cursor: pointer;
38 | padding: 0.25em 0.5em;
39 | border-radius: 0.25em;
40 |
41 | &:hover {
42 | background-color: darken(white, 10%);
43 | }
44 | &.pinned {
45 | background-color: darken(white, 35%);
46 | color: white;
47 | }
48 | p {
49 | pointer-events: none;
50 | }
51 | }
52 | }
53 | }
54 |
55 | .legend {
56 | margin-top: 1em;
57 |
58 | display: flex;
59 | align-items: center;
60 |
61 | .dot {
62 | width: 2em;
63 | height: 2em;
64 |
65 | display: flex;
66 | align-items: center;
67 | justify-content: center;
68 | border: 1px solid red;
69 | border-radius: 50%;
70 | }
71 |
72 | .phrase {
73 | flex: 1;
74 | margin-left: 0.5em;
75 | }
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/src/viz/path_client/chart/update.js:
--------------------------------------------------------------------------------
1 | /* global implementations */
2 |
3 | import { default as _ } from 'lodash'
4 | import { default as d3 } from 'd3'
5 | import { default as Component } from '.'
6 |
7 | // state {impl, digits, amountOfPoints}
8 |
9 | Component.prototype.subscribeToState = function() {
10 | this.options.state$
11 | .map(state => {
12 | let obj = {
13 | state: state,
14 | deAngle: 2 * Math.PI / state.amountOfPoints
15 | }
16 | obj.items = _.map(_.range(state.amountOfPoints), n => ({
17 | x: Math.cos(n * obj.deAngle),
18 | y: Math.sin(n * obj.deAngle)
19 | }))
20 | return obj
21 | })
22 | .subscribe(obj => {
23 | this.data = obj.items
24 | this.sharedState = obj.state
25 |
26 | // line
27 | switch (this.sharedState.impl) {
28 | case 'path.current.path':
29 | this.line = d3.line()
30 | break;
31 | case 'path.withFormat.path':
32 | this.line = implementations.line()
33 | break;
34 | case 'path.withFormat.pathRound':
35 | this.line = implementations.line()
36 | this.line.precision(this.sharedState.digits)
37 | break;
38 | default:
39 | break;
40 | }
41 |
42 | this.line
43 | .x(d => this.scales.x(d.x + this.geometry.jiggleRadius * this.cosAngle))
44 | .y(d => this.scales.y(d.y + this.geometry.jiggleRadius * this.sinAngle))
45 |
46 | this.updateCurveStyle()
47 | })
48 | }
49 |
50 | Component.prototype.startAnimation = function() {
51 | let angularSpeed = 15 // degrees/s
52 | d3.timer(elapsed => {
53 | let angle = (angularSpeed * elapsed / 1000) % 360
54 | this.cosAngle = Math.cos(angle)
55 | this.sinAngle = Math.sin(angle)
56 | if (this.data) {
57 | this.updateCurve() // update + stats measurements
58 | }
59 | })
60 | }
61 |
--------------------------------------------------------------------------------
/src/viz/path_client/chart/geometry.js:
--------------------------------------------------------------------------------
1 | import * as utils from '../../utils'
2 | import { default as Component } from '.'
3 |
4 | Object.defineProperty(Component.prototype, 'geometry', {
5 | get: function () {
6 | if(!this._geometry) {
7 | this._geometry = {
8 | dirty: true,
9 | padding: {top: 20, right: 20, bottom: 60, left: 80},
10 | fontSize: utils.getElementGeometry(this.container.node(),
11 | ['fontSize']
12 | ).fontSize,
13 | jiggleRadius: 0.05
14 | }
15 | }
16 |
17 | if (this._geometry.dirty) {
18 | // container
19 | this._geometry.container = utils.getElementGeometry(
20 | this.container.node(), [
21 | 'paddingBottom',
22 | 'paddingLeft',
23 | 'paddingRight',
24 | 'paddingTop'
25 | ]
26 | )
27 |
28 | // x
29 | this._geometry.width =
30 | this._geometry.container.width
31 | - this._geometry.container.paddingLeft
32 | - this._geometry.container.paddingRight
33 | this._geometry.innerWidth =
34 | this._geometry.width
35 | - this._geometry.padding.left
36 | - this._geometry.padding.right
37 |
38 | // y
39 | this._geometry.height =
40 | this._geometry.container.height
41 | - this._geometry.container.paddingTop
42 | - this._geometry.container.paddingBottom
43 | this._geometry.innerHeight =
44 | this._geometry.height
45 | - this._geometry.padding.top
46 | - this._geometry.padding.bottom
47 |
48 | // origin
49 | this._geometry.origin = [
50 | this._geometry.padding.left + this._geometry.innerWidth / 2,
51 | this._geometry.padding.top + this._geometry.innerHeight / 2
52 | ]
53 | this._geometry.radius = Math.min(
54 | 0.75 * this._geometry.innerWidth / 2,
55 | 0.75 * this._geometry.innerHeight / 2
56 | )
57 |
58 | this._geometry.dirty = false
59 | }
60 |
61 | return this._geometry
62 | }
63 | })
64 |
--------------------------------------------------------------------------------
/src/viz/path/chart/index.less:
--------------------------------------------------------------------------------
1 | .Chart {
2 | width: 100%;
3 | height: 100%;
4 | padding: 0.5em;
5 | font-size: 12px;
6 |
7 | svg {
8 | width: 100%;
9 | height: 100%;
10 |
11 | .trends {
12 | pointer-events: none;
13 |
14 | .curve {
15 | path {
16 | fill: none;
17 | }
18 | text {
19 | fill: black;
20 | stroke: none;
21 | text-anchor: end;
22 | }
23 | }
24 |
25 | .dot {
26 | fill: white;
27 | stroke: black; // fallback
28 |
29 | text {
30 | dominant-baseline: middle;
31 | text-anchor: middle;
32 | stroke: none;
33 | fill: black;
34 | }
35 | }
36 | }
37 |
38 | .axis {
39 | pointer-events: none;
40 |
41 | path {
42 | stroke: lighten(grey, 5%);
43 | }
44 | .tick {
45 | line {
46 | stroke: lighten(grey, 10%);
47 | stroke-opacity: 0.2;
48 | shape-rendering: crispEdges;
49 | }
50 | text {
51 | fill: black;
52 | stroke: none;
53 | }
54 | }
55 | &.x {
56 | .tick {
57 | text {
58 | dominant-baseline: hanging;
59 | }
60 | }
61 | }
62 |
63 | @rangeLabelColor: lighten(black, 60%);
64 |
65 | .label {
66 | fill: black;
67 | stroke: none;
68 | font-size: 1.25em;
69 | dominant-baseline: middle;
70 | text-anchor: middle;
71 |
72 | tspan:nth-child(1) {
73 | font-weight: bold;
74 | }
75 |
76 | &.min {
77 | text-anchor: start;
78 | fill: @rangeLabelColor;
79 | }
80 | &.max {
81 | text-anchor: end;
82 | fill: @rangeLabelColor;
83 | }
84 | }
85 | }
86 |
87 | .sensor {
88 | fill-opacity: 0;
89 | stroke: none;
90 | }
91 | }
92 | }
93 |
--------------------------------------------------------------------------------
/src/viz/path/chart/curves.js:
--------------------------------------------------------------------------------
1 | import { default as Component } from '.'
2 |
3 | Component.prototype.initCurves = function() {
4 | this.trends = this.g.append('g').attr('class', 'trends')
5 | this.curves = this.trends.append('g').attr('class', 'curves')
6 | this.dots = this.trends.append('g').attr('class', 'dots')
7 | }
8 |
9 | Component.prototype.updateCurves = function() {
10 | /* curves */
11 |
12 | this.curve =
13 | this.curves.selectAll('.curve')
14 | .data(this.data.curves, d => d.id)
15 | this.curve.exit().remove()
16 |
17 | let curveEnter = this.curve.enter().append('g').attr('class', 'curve')
18 |
19 | // curve path
20 |
21 | curveEnter.append('path')
22 | .attr('id', d => d.domID)
23 | .style('stroke', d => this.implColor(d.impl))
24 |
25 | // curve label
26 |
27 | curveEnter
28 | .append('text')
29 | .attr('dy', -this.geometry.dotRadiusSafety)
30 | .style('fill', d => this.implColor(d.impl))
31 | .append('textPath')
32 | .attr('startOffset', '90%')
33 | .attr('xlink:href', d => `#${d.domID}`)
34 | .text(d => d.id)
35 |
36 | this.curve = curveEnter.merge(this.curve)
37 |
38 | // dots with text
39 | this.dot = this.dots.selectAll('.dot').data(this.data.points)
40 | this.dot.exit().remove()
41 | let dotEnter = this.dot.enter().append('g').attr('class', 'dot')
42 |
43 | dotEnter.append('circle')
44 | dotEnter.append('text')
45 | .text(d => Math.log10(d.calls))
46 |
47 | this.dot = dotEnter.merge(this.dot)
48 | this.dot.select('circle').style('stroke', d => this.implColor(d.impl))
49 | this.dot.select('text').style('fill', d => this.implColor(d.impl))
50 | }
51 |
52 | Component.prototype.updateCurvesGeometry = function() {
53 | this.curve
54 | .select('path')
55 | .attr('d', d => {
56 | return this.generators.line(d.points)
57 | })
58 |
59 | this.dot
60 | .attr('transform', d => `translate(${[
61 | this.scales.t(d.duration),
62 | this.scales.m(d.heap)
63 | ]})`)
64 | .select('circle')
65 | .attr('r', this.geometry.dotRadiusFocusFactor * this.geometry.dotRadius)
66 | }
67 |
68 | Component.prototype.focusDots = function(focus) {
69 | this.dot
70 | .select('circle')
71 | .attr('r', d => (!focus || (d.calls !== focus.calls))
72 | ? this.geometry.dotRadius
73 | : this.geometry.dotRadiusFocused
74 | )
75 |
76 | this.dot
77 | .select('text')
78 | .attr('font-size', d => (!focus || (d.calls !== focus.calls))
79 | ? null
80 | : `${this.geometry.dotRadiusFocusFactor}em`
81 | )
82 | }
83 |
--------------------------------------------------------------------------------
/src/viz/path_client/app/index.js:
--------------------------------------------------------------------------------
1 | import { default as d3 } from 'd3'
2 | import { default as _ } from 'lodash'
3 | import { default as Controls } from '../controls'
4 | import { default as Chart } from '../chart'
5 | export default App
6 |
7 | function App(options) {
8 | this.options = options
9 | this.setSkeleton()
10 | this.initControls()
11 | this.initState()
12 | this.setStateLoopbacks()
13 | this.initChart()
14 | }
15 |
16 | App.prototype.setSkeleton = function() {
17 | let appdiv = d3.select(this.options.container).append('div').attr('class', 'app')
18 | appdiv.append('div').attr('id', 'Chart')
19 | appdiv.append('div').attr('id', 'Controls')
20 | }
21 |
22 | App.prototype.initControls = function() {
23 | this.controls = new Controls({
24 | container: d3.select('#Controls'),
25 | data: {
26 | impl: [
27 | 'path.current.path',
28 | 'path.withFormat.path',
29 | 'path.withFormat.pathRound',
30 | ],
31 | digits: [null, 0, 1, 2, 3, 4, 5, 10, 15],
32 | amountOfPoints: [
33 | 100,
34 | 1000,
35 | 2000,
36 | 3000,
37 | 4000,
38 | 5000,
39 | 6000,
40 | 7000,
41 | 8000,
42 | 9000,
43 | 10000,
44 | 20000,
45 | 30000,
46 | 40000,
47 | 50000,
48 | 60000,
49 | 70000,
50 | 80000,
51 | 90000,
52 | 100000,
53 | 200000,
54 | 300000,
55 | 400000,
56 | 500000
57 | ]
58 | // amountOfPoints: _.map(_.range(2, 6), n => Math.pow(10, n))
59 | }
60 | })
61 | }
62 |
63 | App.prototype.initState = function() {
64 | this.state$ =
65 | this.controls.getStateHandler$()
66 | .startWith({
67 | impl: 'path.withFormat.pathRound',
68 | digits: null,
69 | amountOfPoints: 100000
70 | })
71 | .scan((state, handler) => handler(state))
72 | }
73 |
74 | App.prototype.setStateLoopbacks = function() {
75 | this.controls.subscribeToState(this.state$)
76 | }
77 |
78 | App.prototype.initChart = function() {
79 | new Chart({
80 | container: d3.select('#Chart'),
81 | state$: this.state$.distinctUntilChanged((a, b) => _.isEqual(a,b)),
82 | allImplementations: [
83 | 'path.current.path',
84 | 'path.withFormat.path',
85 | 'path.withFormat.pathRound',
86 | ]
87 | })
88 | }
89 |
--------------------------------------------------------------------------------
/src/viz/path/chart/geometry.js:
--------------------------------------------------------------------------------
1 | import { default as _ } from 'lodash'
2 | import * as utils from '../../utils'
3 | import { default as Component } from '.'
4 |
5 | Object.defineProperty(Component.prototype, 'geometry', {
6 | get: function () {
7 | if(!this._geometry) {
8 | this._geometry = {
9 | dirty: true,
10 | padding: {top: 20, right: 20, bottom: 60, left: 80},
11 | fontSize: utils.getElementGeometry(this.container.node(),
12 | ['fontSize']
13 | ).fontSize
14 | }
15 | this._geometry.dotRadius = 0.55 * this._geometry.fontSize
16 | this._geometry.dotRadiusSafety = 1.3 * this._geometry.dotRadius
17 | this._geometry.dotRadiusFocusFactor = 1.5
18 | this._geometry.dotRadiusFocused =
19 | this._geometry.dotRadiusFocusFactor * this._geometry.dotRadius
20 |
21 | this._geometry.padding = _.mapValues(this._geometry.padding, n =>
22 | Math.max(n, this._geometry.dotRadiusFocused)
23 | )
24 | this._geometry.origin = [
25 | this.geometry.padding.left,
26 | this.geometry.padding.top,
27 | ]
28 | }
29 |
30 | if (this._geometry.dirty) {
31 | // container
32 | this._geometry.container = utils.getElementGeometry(
33 | this.container.node(), [
34 | 'paddingBottom',
35 | 'paddingLeft',
36 | 'paddingRight',
37 | 'paddingTop'
38 | ]
39 | )
40 |
41 | // x
42 | this._geometry.width =
43 | this._geometry.container.width
44 | - this._geometry.container.paddingLeft
45 | - this._geometry.container.paddingRight
46 | this._geometry.innerWidth =
47 | this._geometry.width
48 | - this._geometry.padding.left
49 | - this._geometry.padding.right
50 |
51 | // y
52 | this._geometry.height =
53 | this._geometry.container.height
54 | - this._geometry.container.paddingTop
55 | - this._geometry.container.paddingBottom
56 | this._geometry.innerHeight =
57 | this._geometry.height
58 | - this._geometry.padding.top
59 | - this._geometry.padding.bottom
60 |
61 | this._geometry.extent = [
62 | [0, 0],
63 | [this._geometry.innerWidth, this._geometry.innerHeight]
64 | ]
65 |
66 | this._geometry.dirty = false
67 | }
68 |
69 | return this._geometry
70 | }
71 | })
72 |
--------------------------------------------------------------------------------
/src/viz/path/app/index.js:
--------------------------------------------------------------------------------
1 | import { default as d3 } from 'd3'
2 | import { default as _ } from 'lodash'
3 | import { Observable } from 'rxjs-es'
4 | import { default as Controls } from '../controls'
5 | import { default as Chart } from '../chart'
6 | export default App
7 |
8 | import './skeleton'
9 |
10 | function App(options) {
11 | this.options = options
12 | this.setSkeleton()
13 | this.load()
14 | }
15 |
16 | App.prototype.load = function() {
17 | this.data$ = Observable.bindNodeCallback(d3.json)('../data/path.json')
18 | this.data$.subscribe(data => {
19 | this.controls = new Controls({
20 | container: d3.select('#Controls'),
21 | data: data
22 | })
23 | this.initState()
24 | this.setStateLoopbacks()
25 | this.initChart()
26 | })
27 | }
28 |
29 | App.prototype.initState = function() {
30 | this.state$ =
31 | this.controls.getStateHandler$()
32 | .startWith({
33 | impl: {
34 | 'path.current.path': {pinned: true},
35 | 'path.withIf.path': {pinned: true},
36 | 'path.withFormat.path': {pinned: true},
37 | // 'path.withFormat.pathRound': {pinned: true}
38 | },
39 | digits: {
40 | null: {pinned: true},
41 | // 5: {pinned: true}
42 | },
43 | command: {
44 | moveTo: {pinned: true},
45 | // lineTo: {pinned: true},
46 | // quadraticCurveTo: {pinned: true},
47 | // rect: {pinned: true},
48 | // bezierCurveTo: {pinned: true},
49 | // arcTo: {pinned: true},
50 | // arc: {pinned: true}
51 | }
52 | })
53 | .scan((state, handler) => handler(state))
54 | // .share()
55 | }
56 |
57 | App.prototype.setStateLoopbacks = function() {
58 | this.controls.subscribeToState(this.state$)
59 | }
60 |
61 | App.prototype.initChart = function() {
62 | new Chart({
63 | container: d3.select('#Chart'),
64 | data$: Observable.combineLatest(this.state$, this.data$, (state, data) => {
65 | let items = data
66 | _.each(state, (dimObj, dimension) => {
67 | let values = _.keys(dimObj)
68 | if (dimension === 'digits') {
69 | values = _.map(values, s =>
70 | s === 'null' ? null : parseInt(s, 10)
71 | )
72 | }
73 | items = _.filter(items, obj => {
74 | return _.includes(values, obj[dimension])
75 | })
76 | })
77 | return {
78 | items: items,
79 | allImplementations: _.keys(_.groupBy(data, obj => obj.impl))
80 | }
81 | })
82 | .distinctUntilChanged((a, b) => _.isEqual(a,b))
83 |
84 | // FIXME fires 2 times as combineLatest subscribe to state$
85 | // as the chart does, but chaining `.share()` to `this.state$` won't
86 | // draw the curves until we mouseover the options in the control panel..
87 | })
88 | }
89 |
--------------------------------------------------------------------------------
/src/viz/path/chart/axes.js:
--------------------------------------------------------------------------------
1 | import { default as Component } from '.'
2 |
3 | Component.prototype.initAxes = function() {
4 | this.axes = {
5 | t: this.g.append('g').attr('class', 'axis x'),
6 | m: this.g.append('g').attr('class', 'axis y')
7 | }
8 |
9 | // x labels
10 | this.tAxisLabel =
11 | this.axes.t.append('g')
12 | .append('text')
13 | .attr('class', 'label')
14 | this.tAxisLabel.append('tspan').text('Duration')
15 | this.tAxisLabel.append('tspan').text('[ s ]').attr('dx', '0.5em')
16 |
17 | this.tAxisLabelMin = this.axes.t.append('g')
18 | this.tAxisLabelMinText =
19 | this.tAxisLabelMin.append('text').attr('class', 'label min')
20 |
21 | this.tAxisLabelMax = this.axes.t.append('g')
22 | this.tAxisLabelMaxText =
23 | this.tAxisLabelMax.append('text').attr('class', 'label max')
24 |
25 | // y labels
26 | this.mAxisLabel =
27 | this.axes.m.append('g').attr('class', 'label')
28 | .append('text')
29 | this.mAxisLabel.append('tspan').text('Heap')
30 | this.mAxisLabel.append('tspan').text('[ bytes ]').attr('dx', '0.5em')
31 |
32 | this.mAxisLabelMin = this.axes.m.append('g')
33 | this.mAxisLabelMinText =
34 | this.mAxisLabelMin.append('text').attr('class', 'label min')
35 |
36 | this.mAxisLabelMax = this.axes.t.append('g')
37 | this.mAxisLabelMaxText =
38 | this.mAxisLabelMax.append('text').attr('class', 'label max')
39 | }
40 |
41 | Component.prototype.updateAxes = function() {
42 | /* x */
43 |
44 | this.axes.t
45 | .attr('transform', `translate(${[0,this.geometry.innerHeight]})`)
46 | .call(this.generators.axes.t)
47 |
48 | // dots with low memory values might overlap x axis ticks
49 | this.axes.t.selectAll('.tick text')
50 | .attr('y', this.geometry.dotRadiusSafety)
51 |
52 | // labels
53 | this.tAxisLabel
54 | .attr('transform', `translate(${[
55 | this.geometry.innerWidth/2,
56 | 0.65 * this.geometry.padding.bottom
57 | ]})`)
58 |
59 | this.tAxisLabelMin
60 | .attr('transform', `translate(${[0, 0.65*this.geometry.padding.bottom]})`)
61 | this.tAxisLabelMinText
62 | .text(this.data.tExtent[0]
63 | ? `|< 1e${Math.log10(this.data.tExtent[0]).toFixed(1)}`
64 | : ''
65 | )
66 |
67 | this.tAxisLabelMax
68 | .attr('transform', `translate(${[
69 | this.geometry.innerWidth,
70 | 0.65 * this.geometry.padding.bottom]})`
71 | )
72 | this.tAxisLabelMaxText
73 | .text(this.data.tExtent[1]
74 | ? `1e${Math.log10(this.data.tExtent[1]).toFixed(1)} >|`
75 | : ''
76 | )
77 |
78 | /* y */
79 |
80 | this.axes.m
81 | // .attr('transform', `translate(${[0,this.geometry.innerHeight]})`)
82 | .call(this.generators.axes.m)
83 |
84 | // dots with low time values might overlap y axis ticks
85 | this.axes.m.selectAll('.tick text')
86 | .attr('x', -this.geometry.dotRadiusSafety)
87 |
88 | this.mAxisLabel
89 | .attr('transform', `translate(${[
90 | -0.65 * this.geometry.padding.left,
91 | this.geometry.innerHeight/2
92 | ]}) rotate(-90)`)
93 |
94 | this.mAxisLabelMin
95 | .attr('transform', `translate(${[
96 | -0.65 * this.geometry.padding.left,
97 | this.geometry.innerHeight
98 | ]}) rotate(-90)`)
99 | this.mAxisLabelMinText
100 | .text(this.data.mExtent[0]
101 | ? `|< 1e${Math.log10(this.data.mExtent[0]).toFixed(1)}`
102 | : ''
103 | )
104 |
105 | this.mAxisLabelMax
106 | .attr('transform', `translate(${[
107 | -0.65 * this.geometry.padding.left,
108 | -this.geometry.innerHeight
109 | ]}) rotate(-90)`)
110 | this.mAxisLabelMaxText
111 | .text(this.data.mExtent[1]
112 | ? `1e${Math.log10(this.data.mExtent[1]).toFixed(1)} >|`
113 | : ''
114 | )
115 | }
116 |
--------------------------------------------------------------------------------
/src/bench/round.js:
--------------------------------------------------------------------------------
1 | /*
2 | node bench/round.js
3 | to be run as idle as possible:
4 | - charger connected
5 | - no wifi | sleep mode
6 | - no or limited amount of open apps | user activities
7 | */
8 |
9 | const fs = require('fs')
10 | const _ = require('lodash')
11 | const esprima = require('esprima')
12 | const escodegen = require('escodegen')
13 | const benchmark = require('benchmark')
14 | const bundle = require('../../build/bundle')
15 |
16 | const RESULTS_PATH = './data/rounding.json'
17 | const N = 10.1234567890123456
18 | const TRANSFORM = [null, 'CoerceNumber', 'CoerceString']
19 | const IMPLEMENTATIONS = ['round', 'roundMDN', 'fixed']
20 | const DIGITS = [0, 5, 10, 15]
21 |
22 | let testData
23 | let results = []
24 |
25 | let suite = new benchmark.Suite('rounding')
26 | .on('start', function() {
27 | console.log(`Executing rounding tests...`)
28 | })
29 | .on('cycle', function(event) {
30 | console.log(String(event.target));
31 | })
32 | .on('complete', () => {
33 | fs.writeFile(RESULTS_PATH, JSON.stringify(results, null, 2), err => {
34 | if (err) {throw err}
35 | console.log('Saved results in:', RESULTS_PATH)
36 | })
37 | })
38 |
39 | // generate test functions and add themto the suite
40 | _.each(IMPLEMENTATIONS, impl => {
41 | _.each(TRANSFORM, transform => {
42 | _.each(DIGITS, digits => {
43 | suite.add(
44 | transform ? `${impl}.${transform}.${digits}` : `${impl}.${digits}`,
45 | exec(transform, impl, digits),
46 | {
47 | onStart: () => {
48 | testData = {
49 | impl: impl,
50 | transform: transform,
51 | digits: digits
52 | }
53 | },
54 | onComplete: (event) => {
55 | testData.duration = event.target.times.period // secs
56 | results.push(testData)
57 | checkOutput(transform, impl, digits)()
58 | },
59 | onError: (event) => {
60 | // FIXME log arrors and save in file
61 | console.log('*************************************')
62 | console.log(event)
63 | console.log('*************************************')
64 | }
65 | }
66 | )
67 | })
68 | })
69 | })
70 |
71 | suite.run()
72 |
73 | function exec(transform, implementation, digits) {
74 | let afuncAST = esprima.parse(`() => {}`).body[0]
75 | afuncAST.expression.body.body.push(
76 | esprima.parse(
77 | roundingCode(transform, implementation, digits)
78 | )
79 | )
80 | return eval(escodegen.generate(afuncAST))
81 | }
82 |
83 | // to check the result, append a console.log() to the exec() function
84 | function checkOutput(transform, implementation, digits) {
85 | let afuncAST = esprima.parse(`() => {}`).body[0]
86 | let code = roundingCode(transform, implementation, digits)
87 | let testName = transform
88 | ? `${implementation}.${transform}.${digits}`
89 | : `${implementation}.${digits}`
90 |
91 | afuncAST.expression.body.body.push(
92 | esprima.parse(`console.log('${testName}: ${N} => ', ${code})`)
93 | )
94 | return eval(escodegen.generate(afuncAST))
95 | }
96 |
97 | function roundingCode(transform, implementation, digits) {
98 | let transformedN
99 | switch (transform) {
100 | case null:
101 | transformedN = `${N}`
102 | break;
103 | case 'CoerceNumber':
104 | transformedN = `+${N}`
105 | break;
106 | case 'CoerceString':
107 | transformedN = `+"${N}"`
108 | break;
109 | default:
110 | break;
111 | }
112 |
113 | let code
114 | switch (implementation) {
115 | case 'round':
116 | code = `bundle.round(${transformedN}, ${digits})`
117 | break;
118 | case 'roundMDN':
119 | code = `bundle.roundMDN(${transformedN}, ${digits})`
120 | break;
121 | case 'fixed':
122 | code = `${N}.toFixed(${digits})`
123 | break;
124 | default:
125 | break;
126 | }
127 | return code
128 | }
129 |
--------------------------------------------------------------------------------
/data/rounding.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "impl": "round",
4 | "transform": null,
5 | "digits": 0,
6 | "duration": 1.5478552534985366e-8
7 | },
8 | {
9 | "impl": "round",
10 | "transform": null,
11 | "digits": 5,
12 | "duration": 1.5977351977287934e-8
13 | },
14 | {
15 | "impl": "round",
16 | "transform": null,
17 | "digits": 10,
18 | "duration": 1.6534258116654933e-8
19 | },
20 | {
21 | "impl": "round",
22 | "transform": null,
23 | "digits": 15,
24 | "duration": 1.5641545992664062e-8
25 | },
26 | {
27 | "impl": "round",
28 | "transform": "CoerceNumber",
29 | "digits": 0,
30 | "duration": 1.536461834537893e-8
31 | },
32 | {
33 | "impl": "round",
34 | "transform": "CoerceNumber",
35 | "digits": 5,
36 | "duration": 1.7060544964127023e-8
37 | },
38 | {
39 | "impl": "round",
40 | "transform": "CoerceNumber",
41 | "digits": 10,
42 | "duration": 1.586134681073694e-8
43 | },
44 | {
45 | "impl": "round",
46 | "transform": "CoerceNumber",
47 | "digits": 15,
48 | "duration": 1.575603096778826e-8
49 | },
50 | {
51 | "impl": "round",
52 | "transform": "CoerceString",
53 | "digits": 0,
54 | "duration": 1.5284206065782193e-8
55 | },
56 | {
57 | "impl": "round",
58 | "transform": "CoerceString",
59 | "digits": 5,
60 | "duration": 1.5749985193735745e-8
61 | },
62 | {
63 | "impl": "round",
64 | "transform": "CoerceString",
65 | "digits": 10,
66 | "duration": 1.562874961546658e-8
67 | },
68 | {
69 | "impl": "round",
70 | "transform": "CoerceString",
71 | "digits": 15,
72 | "duration": 1.5657167562737306e-8
73 | },
74 | {
75 | "impl": "roundMDN",
76 | "transform": null,
77 | "digits": 0,
78 | "duration": 1.450359351089088e-8
79 | },
80 | {
81 | "impl": "roundMDN",
82 | "transform": null,
83 | "digits": 5,
84 | "duration": 1.4451925870556859e-8
85 | },
86 | {
87 | "impl": "roundMDN",
88 | "transform": null,
89 | "digits": 10,
90 | "duration": 1.4274372678482219e-8
91 | },
92 | {
93 | "impl": "roundMDN",
94 | "transform": null,
95 | "digits": 15,
96 | "duration": 1.4393497266734521e-8
97 | },
98 | {
99 | "impl": "roundMDN",
100 | "transform": "CoerceNumber",
101 | "digits": 0,
102 | "duration": 1.4569680130963163e-8
103 | },
104 | {
105 | "impl": "roundMDN",
106 | "transform": "CoerceNumber",
107 | "digits": 5,
108 | "duration": 1.4082099685837212e-8
109 | },
110 | {
111 | "impl": "roundMDN",
112 | "transform": "CoerceNumber",
113 | "digits": 10,
114 | "duration": 1.3886912575203212e-8
115 | },
116 | {
117 | "impl": "roundMDN",
118 | "transform": "CoerceNumber",
119 | "digits": 15,
120 | "duration": 1.396974892845556e-8
121 | },
122 | {
123 | "impl": "roundMDN",
124 | "transform": "CoerceString",
125 | "digits": 0,
126 | "duration": 1.4050605949870337e-8
127 | },
128 | {
129 | "impl": "roundMDN",
130 | "transform": "CoerceString",
131 | "digits": 5,
132 | "duration": 1.4690637856826566e-8
133 | },
134 | {
135 | "impl": "roundMDN",
136 | "transform": "CoerceString",
137 | "digits": 10,
138 | "duration": 1.4588132629362375e-8
139 | },
140 | {
141 | "impl": "roundMDN",
142 | "transform": "CoerceString",
143 | "digits": 15,
144 | "duration": 1.4451615175163754e-8
145 | },
146 | {
147 | "impl": "fixed",
148 | "transform": null,
149 | "digits": 0,
150 | "duration": 3.4691750980863377e-7
151 | },
152 | {
153 | "impl": "fixed",
154 | "transform": null,
155 | "digits": 5,
156 | "duration": 3.7675478035984576e-7
157 | },
158 | {
159 | "impl": "fixed",
160 | "transform": null,
161 | "digits": 10,
162 | "duration": 3.8248522973049554e-7
163 | },
164 | {
165 | "impl": "fixed",
166 | "transform": null,
167 | "digits": 15,
168 | "duration": 4.193853086654978e-7
169 | },
170 | {
171 | "impl": "fixed",
172 | "transform": "CoerceNumber",
173 | "digits": 0,
174 | "duration": 3.346735656669211e-7
175 | },
176 | {
177 | "impl": "fixed",
178 | "transform": "CoerceNumber",
179 | "digits": 5,
180 | "duration": 3.653331792865546e-7
181 | },
182 | {
183 | "impl": "fixed",
184 | "transform": "CoerceNumber",
185 | "digits": 10,
186 | "duration": 3.7477098853450743e-7
187 | },
188 | {
189 | "impl": "fixed",
190 | "transform": "CoerceNumber",
191 | "digits": 15,
192 | "duration": 3.972308549892275e-7
193 | },
194 | {
195 | "impl": "fixed",
196 | "transform": "CoerceString",
197 | "digits": 0,
198 | "duration": 3.3094010870576886e-7
199 | },
200 | {
201 | "impl": "fixed",
202 | "transform": "CoerceString",
203 | "digits": 5,
204 | "duration": 3.6704845222098596e-7
205 | },
206 | {
207 | "impl": "fixed",
208 | "transform": "CoerceString",
209 | "digits": 10,
210 | "duration": 3.755182609688008e-7
211 | },
212 | {
213 | "impl": "fixed",
214 | "transform": "CoerceString",
215 | "digits": 15,
216 | "duration": 3.99749975190138e-7
217 | }
218 | ]
--------------------------------------------------------------------------------
/src/viz/path_client/controls/index.js:
--------------------------------------------------------------------------------
1 | import { default as _ } from 'lodash'
2 | import { default as d3 } from 'd3'
3 | import { Observable } from 'rxjs-es'
4 | export default Component
5 | import './colors'
6 |
7 | function Component(options) {
8 | this.name = 'Controls'
9 | this.options = options
10 | this.init()
11 | this.setStateHandler$()
12 | }
13 |
14 | Component.prototype.init = function() {
15 | this.container = this.options.container.append('div').attr('class', this.name)
16 |
17 | let panel =
18 | this.container.selectAll('.panel')
19 | .data(
20 | _.map(this.options.data, (values, key) => ({
21 | key: key,
22 | values: _.map(values, value => ({key: key, value: value}))
23 | })),
24 | d => d.key
25 | )
26 |
27 | panel.exit().remove()
28 |
29 | let panelEnter =
30 | panel.enter()
31 | .append('div')
32 | .attr('class', 'panel')
33 |
34 | panelEnter
35 | .append('p')
36 | .attr('class', 'title')
37 | .text(d => ({
38 | impl: 'Implementation',
39 | digits: 'Digits',
40 | amountOfPoints: 'Amount of points'
41 | }[d.key]))
42 |
43 | this.valueDiv =
44 | panelEnter
45 | .selectAll('.row')
46 | .data(d => d.values)
47 |
48 | let valueEnter =
49 | this.valueDiv.enter()
50 | .append('div')
51 | .attr('class', 'row')
52 |
53 | valueEnter
54 | .filter(d => d.key === 'impl')
55 | .append('div')
56 | .attr('class', 'dot')
57 | .style('background-color', d => {
58 | return d.key === 'impl' ? this.implColor(d.value) : null
59 | })
60 |
61 | valueEnter
62 | .append('div')
63 | .attr('class', 'value')
64 | .append('p')
65 | .text(d => {
66 | let value
67 | switch (d.key) {
68 | case 'impl': {
69 | let d_value = d.value.split('.').slice(1).join('.')
70 | switch (d_value) {
71 | case 'current.path':
72 | case 'withFormat.path':
73 | value = `${d_value} ( null )`
74 | break;
75 | case 'withIf.path':
76 | value = `${d_value} ( null | digits )`
77 | break;
78 | case 'withFormat.pathRound':
79 | value = `${d_value} ( null | digits )`
80 | break;
81 | default:
82 | break;
83 | }
84 | break;
85 | }
86 | default:
87 | value = String(d.value)
88 | }
89 | return value
90 | })
91 |
92 | this.valueDiv = this.valueDiv.merge(valueEnter)
93 | }
94 |
95 | Component.prototype.setStateHandler$ = function() {
96 | this.stateHandler$ = Observable.merge(
97 | ..._.map(this.valueDiv.nodes(), node => {
98 | let d = d3.select(node).datum()
99 | return Observable
100 | .fromEvent(node, 'click')
101 | .map(() =>
102 | state => {
103 | let currentImpl = state.impl
104 |
105 | let update = _.pick(state, d.key)
106 | update[d.key] = d.value
107 |
108 | switch (d.key) {
109 | case 'impl':
110 | switch (d.value) {
111 | case 'path.current.path':
112 | case 'path.withFormat.path':
113 | update.digits = null
114 | break;
115 | default:
116 | break;
117 | }
118 | break;
119 | case 'digits':
120 | switch (currentImpl) {
121 | case 'path.current.path':
122 | case 'path.withFormat.path':
123 | update.digits = null
124 | break;
125 | default:
126 | break;
127 | }
128 | break;
129 | default:
130 | break;
131 | }
132 |
133 | console.log('update', update)
134 |
135 | return Object.assign({}, state, update)
136 | }
137 | )
138 | })
139 | )
140 | }
141 |
142 | Component.prototype.getStateHandler$ = function() {
143 | return this.stateHandler$
144 | }
145 |
146 | Component.prototype.subscribeToState = function(state$) {
147 | state$.subscribe(state => {
148 | console.log(state)
149 |
150 | this.valueDiv.select('.value')
151 | .classed('pinned', d => {
152 | return (state[d.key] === d.value)
153 | })
154 | })
155 | }
156 |
--------------------------------------------------------------------------------
/src/implementations/path/withFormat.js:
--------------------------------------------------------------------------------
1 | import {round} from '../utils/round'
2 |
3 | var pi = Math.PI,
4 | tau = 2 * pi,
5 | epsilon = 1e-6,
6 | tauEpsilon = tau - epsilon;
7 |
8 | function Path() {
9 | this._x0 = this._y0 = // start of current subpath
10 | this._x1 = this._y1 = null; // end of current subpath
11 | this._ = "";
12 | }
13 |
14 | Path.prototype = path.prototype = {
15 | constructor: Path,
16 | _format: function(x) {
17 | return x;
18 | },
19 | moveTo: function(x, y) {
20 | this._ += "M" + this._format(this._x0 = this._x1 = +x) + "," + this._format(this._y0 = this._y1 = +y);
21 | },
22 | closePath: function() {
23 | if (this._x1 !== null) {
24 | this._x1 = this._x0, this._y1 = this._y0;
25 | this._ += "Z";
26 | }
27 | },
28 | lineTo: function(x, y) {
29 | this._ += "L" + this._format(this._x1 = +x) + "," + this._format(this._y1 = +y);
30 | },
31 | quadraticCurveTo: function(x1, y1, x, y) {
32 | this._ += "Q" + this._format(+x1) + "," + this._format(+y1) + "," + this._format(this._x1 = +x) + "," + this._format(this._y1 = +y);
33 | },
34 | bezierCurveTo: function(x1, y1, x2, y2, x, y) {
35 | this._ += "C" + this._format(+x1) + "," + this._format(+y1) + "," + this._format(+x2) + "," + this._format(+y2) + "," + this._format(this._x1 = +x) + "," + this._format(this._y1 = +y);
36 | },
37 | arcTo: function(x1, y1, x2, y2, r) {
38 | x1 = +x1, y1 = +y1, x2 = +x2, y2 = +y2, r = +r;
39 | var x0 = this._x1,
40 | y0 = this._y1,
41 | x21 = x2 - x1,
42 | y21 = y2 - y1,
43 | x01 = x0 - x1,
44 | y01 = y0 - y1,
45 | l01_2 = x01 * x01 + y01 * y01;
46 |
47 | // Is the radius negative? Error.
48 | if (r < 0) throw new Error("negative radius: " + r);
49 |
50 | // Is this path empty? Move to (x1,y1).
51 | if (this._x1 === null) {
52 | this._ += "M" + this._format(this._x1 = x1) + "," + this._format(this._y1 = y1);
53 | }
54 |
55 | // Or, is (x1,y1) coincident with (x0,y0)? Do nothing.
56 | else if (!(l01_2 > epsilon)) {}
57 |
58 | // Or, are (x0,y0), (x1,y1) and (x2,y2) collinear?
59 | // Equivalently, is (x1,y1) coincident with (x2,y2)?
60 | // Or, is the radius zero? Line to (x1,y1).
61 | else if (!(Math.abs(y01 * x21 - y21 * x01) > epsilon) || !r) {
62 | this._ += "L" + this._format(this._x1 = x1) + "," + this._format(this._y1 = y1);
63 | }
64 |
65 | // Otherwise, draw an arc!
66 | else {
67 | var x20 = x2 - x0,
68 | y20 = y2 - y0,
69 | l21_2 = x21 * x21 + y21 * y21,
70 | l20_2 = x20 * x20 + y20 * y20,
71 | l21 = Math.sqrt(l21_2),
72 | l01 = Math.sqrt(l01_2),
73 | l = r * Math.tan((pi - Math.acos((l21_2 + l01_2 - l20_2) / (2 * l21 * l01))) / 2),
74 | t01 = l / l01,
75 | t21 = l / l21;
76 |
77 | // If the start tangent is not coincident with (x0,y0), line to.
78 | if (Math.abs(t01 - 1) > epsilon) {
79 | this._ += "L" + this._format(x1 + t01 * x01) + "," + this._format(y1 + t01 * y01);
80 | }
81 |
82 | this._ += "A" + this._format(r) + "," + this._format(r) + ",0,0," + (+(y01 * x20 > x01 * y20)) + "," + this._format(this._x1 = x1 + t21 * x21) + "," + this._format(this._y1 = y1 + t21 * y21);
83 | }
84 | },
85 | arc: function(x, y, r, a0, a1, ccw) {
86 | x = +x, y = +y, r = +r;
87 | var dx = r * Math.cos(a0),
88 | dy = r * Math.sin(a0),
89 | x0 = x + dx,
90 | y0 = y + dy,
91 | cw = 1 ^ ccw,
92 | da = ccw ? a0 - a1 : a1 - a0;
93 |
94 | // Is the radius negative? Error.
95 | if (r < 0) throw new Error("negative radius: " + r);
96 |
97 | // Is this path empty? Move to (x0,y0).
98 | if (this._x1 === null) {
99 | this._ += "M" + this._format(x0) + "," + this._format(y0);
100 | }
101 |
102 | // Or, is (x0,y0) not coincident with the previous point? Line to (x0,y0).
103 | else if (Math.abs(this._x1 - x0) > epsilon || Math.abs(this._y1 - y0) > epsilon) {
104 | this._ += "L" + this._format(x0) + "," + this._format(y0);
105 | }
106 |
107 | // Is this arc empty? We’re done.
108 | if (!r) return;
109 |
110 | // Is this a complete circle? Draw two arcs to complete the circle.
111 | if (da > tauEpsilon) {
112 | this._ += "A" + this._format(r) + "," + this._format(r) + ",0,1," + cw + "," + this._format(x - dx) + "," + this._format(y - dy) + "A" + this._format(r) + "," + this._format(r) + ",0,1," + cw + "," + this._format(this._x1 = x0) + "," + this._format(this._y1 = y0);
113 | }
114 |
115 | // Otherwise, draw an arc!
116 | else {
117 | if (da < 0) da = da % tau + tau;
118 | this._ += "A" + this._format(r) + "," + this._format(r) + ",0," + (+(da >= pi)) + "," + cw + "," + this._format(this._x1 = x + r * Math.cos(a1)) + "," + this._format(this._y1 = y + r * Math.sin(a1));
119 | }
120 | },
121 | rect: function(x, y, w, h) {
122 | this._ += "M" + this._format(this._x0 = this._x1 = +x) + "," + this._format(this._y0 = this._y1 = +y) + "h" + this._format(+w) + "v" + this._format(+h) + "h" + this._format(-w) + "Z";
123 | },
124 | toString: function() {
125 | return this._;
126 | }
127 | };
128 |
129 | export function path() {
130 | return new Path;
131 | };
132 |
133 | export function pathCoerceFixed(digits) {
134 | var path = new Path;
135 | (digits = +digits).toFixed(digits); // Validate digits.
136 | path._format = function(x) { return +x.toFixed(digits); };
137 | return path;
138 | }
139 | export function pathFixed(digits) {
140 | var path = new Path;
141 | (digits = +digits).toFixed(digits); // Validate digits.
142 | path._format = function(x) { return x.toFixed(digits); };
143 | return path;
144 | }
145 |
146 | export function pathCoerceRound(digits) {
147 | var path = new Path;
148 | (digits = +digits).toFixed(digits); // Validate digits.
149 | path._format = function(x) { return round(+x, digits); };
150 | return path;
151 | }
152 | export function pathRound(digits) {
153 | var path = new Path;
154 | (digits = +digits).toFixed(digits); // Validate digits.
155 | path._format = function(x) { return round(x, digits); };
156 | return path;
157 | }
158 |
--------------------------------------------------------------------------------
/src/implementations/path/withIf.js:
--------------------------------------------------------------------------------
1 | import {round as R} from '../utils/round'
2 |
3 | var pi = Math.PI,
4 | tau = 2 * pi,
5 | epsilon = 1e-6,
6 | tauEpsilon = tau - epsilon;
7 |
8 | function Path(digits) {
9 | this._d = digits;
10 | this._x0 = this._y0 = // start of current subpath
11 | this._x1 = this._y1 = null; // end of current subpath
12 | this._ = "";
13 | }
14 |
15 | Path.prototype = path.prototype = {
16 | constructor: Path,
17 | moveTo: function(x, y) {
18 | if (this._d) {
19 | this._ += `M${R(this._x0 = this._x1 = x, this._d)},${R(this._y0 = this._y1 = y, this._d)}`;
20 | } else {
21 | this._ += `M${this._x0 = this._x1 = x},${this._y0 = this._y1 = y}`;
22 | }
23 | },
24 | closePath: function() {
25 | if (this._x1 !== null) {
26 | this._x1 = this._x0, this._y1 = this._y0;
27 | this._ += "Z";
28 | }
29 | },
30 | lineTo: function(x, y) {
31 | if (this._d) {
32 | this._ += `L${R(this._x1 = x, this._d)},${R(this._y1 = y, this._d)}`;
33 | } else {
34 | this._ += `L${this._x1 = x},${this._y1 = y}`;
35 | }
36 | },
37 | quadraticCurveTo: function(x1, y1, x, y) {
38 | if (this._d) {
39 | this._ += `Q${R(x1, this._d)},${R(y1, this._d)},${R(this._x1 = x, this._d)},${R(this._y1 = y, this._d)}`;
40 | } else {
41 | this._ += `Q${x1},${y1},${this._x1 = x},${this._y1 = y}`;
42 | }
43 | },
44 | bezierCurveTo: function(x1, y1, x2, y2, x, y) {
45 | if (this._d) {
46 | this._ += `C${R(x1, this._d)},${R(y1, this._d)},${R(x2, this._d)},${R(y2, this._d)},${R(this._x1 = x, this._d)},${R(this._y1 = y, this._d)}`;
47 | } else {
48 | this._ += `C${x1},${y1},${x2},${y2},${this._x1 = x},${this._y1 = y}`;
49 | }
50 | },
51 | arcTo: function(x1, y1, x2, y2, r) {
52 | x1 = +x1, y1 = +y1, x2 = +x2, y2 = +y2, r = +r;
53 | var x0 = this._x1,
54 | y0 = this._y1,
55 | x21 = x2 - x1,
56 | y21 = y2 - y1,
57 | x01 = x0 - x1,
58 | y01 = y0 - y1,
59 | l01_2 = x01 * x01 + y01 * y01;
60 |
61 | // Is the radius negative? Error.
62 | if (r < 0) throw new Error("negative radius: " + r);
63 |
64 | // Is this path empty? Move to (x1,y1).
65 | if (this._x1 === null) {
66 | // this._ += "M" + this._format(this._x1 = x1) + "," + this._format(this._y1 = y1);
67 | this.moveTo(x1, y1);
68 | }
69 |
70 | // Or, is (x1,y1) coincident with (x0,y0)? Do nothing.
71 | else if (!(l01_2 > epsilon)) {}
72 |
73 | // Or, are (x0,y0), (x1,y1) and (x2,y2) collinear?
74 | // Equivalently, is (x1,y1) coincident with (x2,y2)?
75 | // Or, is the radius zero? Line to (x1,y1).
76 | else if (!(Math.abs(y01 * x21 - y21 * x01) > epsilon) || !r) {
77 | // this._ += "L" + this._format(this._x1 = x1) + "," + this._format(this._y1 = y1);
78 | this.lineTo(x1, y1);
79 | }
80 |
81 | // Otherwise, draw an arc!
82 | else {
83 | var x20 = x2 - x0,
84 | y20 = y2 - y0,
85 | l21_2 = x21 * x21 + y21 * y21,
86 | l20_2 = x20 * x20 + y20 * y20,
87 | l21 = Math.sqrt(l21_2),
88 | l01 = Math.sqrt(l01_2),
89 | l = r * Math.tan((pi - Math.acos((l21_2 + l01_2 - l20_2) / (2 * l21 * l01))) / 2),
90 | t01 = l / l01,
91 | t21 = l / l21;
92 |
93 | // If the start tangent is not coincident with (x0,y0), line to.
94 | if (Math.abs(t01 - 1) > epsilon) {
95 | this.lineTo(x1 + t01 * x01, y1 + t01 * y01);
96 | }
97 |
98 | if (this._d) {
99 | this._ += `A${R(r, this._d)},${R(r, this._d)},0,0,${+(y01 * x20 > x01 * y20)},${R(this._x1 = x1 + t21 * x21, this._d)},${R(this._y1 = y1 + t21 * y21, this._d)}`;
100 | } else {
101 | this._ += `A${r},${r},0,0,${+(y01 * x20 > x01 * y20)},${this._x1 = x1 + t21 * x21},${this._y1 = y1 + t21 * y21}`;
102 | }
103 | }
104 | },
105 | arc: function(x, y, r, a0, a1, ccw) {
106 | x = +x, y = +y, r = +r;
107 | var dx = r * Math.cos(a0),
108 | dy = r * Math.sin(a0),
109 | x0 = x + dx,
110 | y0 = y + dy,
111 | cw = 1 ^ ccw,
112 | da = ccw ? a0 - a1 : a1 - a0;
113 |
114 | // Is the radius negative? Error.
115 | if (r < 0) throw new Error("negative radius: " + r);
116 |
117 | // Is this path empty? Move to (x0,y0).
118 | if (this._x1 === null) {
119 | this.moveTo(x0, y0);
120 | }
121 |
122 | // Or, is (x0,y0) not coincident with the previous point? Line to (x0,y0).
123 | else if (Math.abs(this._x1 - x0) > epsilon || Math.abs(this._y1 - y0) > epsilon) {
124 | this.lineTo(x0, y0);
125 | }
126 |
127 | // Is this arc empty? We’re done.
128 | if (!r) return;
129 |
130 | // Is this a complete circle? Draw two arcs to complete the circle.
131 | if (da > tauEpsilon) {
132 | if (this._d) {
133 | this._ += `A${r = R(r, this._d)},${r},0,1,${cw},${R(x - dx, this._d)},${R(y - dy, this._d)},A${r},${r},0,1,${cw},${R(this._x1 = x0, this._d)},${R(this._y1 = y0, this._d)}`;
134 | } else {
135 | this._ += `A${r},${r},0,1,${cw},${x - dx},${y - dy},A${r},${r},0,1,${cw},${this._x1 = x0},${this._y1 = y0}`;
136 | }
137 | }
138 |
139 | // Otherwise, draw an arc!
140 | else {
141 | if (da < 0) da = da % tau + tau;
142 | if (this._d) {
143 | this._ += `A${R(r, this._d)},${R(r, this._d)},0,${+(da >= pi)},${cw},${R(this._x1 = x + r * Math.cos(a1), this._d)},${R(this._y1 = y + r * Math.sin(a1), this._d)}`;
144 | } else {
145 | this._ += `A${r},${r},0,${+(da >= pi)},${cw},${this._x1 = x + r * Math.cos(a1)},${this._y1 = y + r * Math.sin(a1)}`;
146 | }
147 | }
148 | },
149 | rect: function(x, y, w, h) {
150 | if (this._d) {
151 | this._ += `M${R(this._x0 = this._x1 = x, this._d)},${R(this._y0 = this._y1 = y, this._d)}h${R(w, this._d)}v${R(h, this._d)}h${R(-w, this._d)}Z`;
152 | } else {
153 | this._ += `M${this._x0 = this._x1 = x},${this._y0 = this._y1 = y}h${w}v${h}h${-w}Z`;
154 | }
155 | },
156 | toString: function() {
157 | return this._;
158 | }
159 | };
160 |
161 | export function path(digits) {
162 | (digits = +digits).toFixed(digits); // Validate digits.
163 | return new Path(digits);
164 | };
165 |
--------------------------------------------------------------------------------
/src/viz/path/controls/index.js:
--------------------------------------------------------------------------------
1 | import { default as _ } from 'lodash'
2 | import { default as d3 } from 'd3'
3 | import { Observable } from 'rxjs-es'
4 | export default Component
5 | import './colors'
6 |
7 | function Component(options) {
8 | this.name = 'Controls'
9 | this.options = options
10 | this.init()
11 | this.setStateHandler$()
12 | }
13 |
14 | Component.prototype.init = function() {
15 | this.container = this.options.container.append('div').attr('class', this.name)
16 |
17 | let panel =
18 | this.container.selectAll('.panel')
19 | .data(
20 | _.map(['impl', 'digits', 'command'], key =>
21 | ({
22 | key: key,
23 | values: _.chain(this.options.data)
24 | .groupBy(key)
25 | .keys()
26 | .map(value => ({
27 | key: key,
28 | value: key === 'digits'
29 | ? value === 'null'
30 | ? null
31 | : parseInt(value, 10)
32 | : value
33 | }))
34 | .value()
35 | })
36 | ),
37 | d => d.key
38 | )
39 |
40 | panel.exit().remove()
41 |
42 | let panelEnter =
43 | panel.enter()
44 | .append('div')
45 | .attr('class', 'panel')
46 |
47 | panelEnter
48 | .append('p')
49 | .attr('class', 'title')
50 | .text(d => ({
51 | impl: 'Implementation',
52 | digits: 'Digits',
53 | command: 'Command'
54 | }[d.key]))
55 |
56 | this.valueDiv =
57 | panelEnter
58 | .selectAll('.row')
59 | .data(d => d.values)
60 |
61 | let valueEnter =
62 | this.valueDiv.enter()
63 | .append('div')
64 | .attr('class', 'row')
65 |
66 | valueEnter
67 | .filter(d => d.key === 'impl')
68 | .append('div')
69 | .attr('class', 'dot')
70 | .style('background-color', d => {
71 | return d.key === 'impl' ? this.implColor(d.value) : null
72 | })
73 |
74 | valueEnter
75 | .append('div')
76 | .attr('class', 'value')
77 | .append('p')
78 | .text(d => {
79 | let value
80 | switch (d.key) {
81 | case 'impl': {
82 | let d_value = d.value.split('.').slice(1).join('.')
83 | switch (d_value) {
84 | case 'current.path':
85 | case 'withFormat.path':
86 | value = `${d_value} ( null )`
87 | break;
88 | case 'withIf.path':
89 | value = `${d_value} ( null | digits )`
90 | break;
91 | case 'withFormat.pathRound':
92 | case 'withFormat.pathCoerceFixed':
93 | case 'withFormat.pathFixed':
94 | case 'withFormat.pathCoerceRound':
95 | value = `${d_value} ( digits )`
96 | break;
97 | default:
98 | break;
99 | }
100 | break;
101 | }
102 | default:
103 | value = String(d.value)
104 | }
105 | return value
106 | })
107 |
108 | this.valueDiv = this.valueDiv.merge(valueEnter)
109 |
110 | /* mini legend */
111 |
112 | let legend = this.container.append('div').attr('class', 'legend')
113 |
114 | legend
115 | .append('div').attr('class', 'dot')
116 | .append('p').text('N')
117 |
118 | legend
119 | .append('div').attr('class', 'phrase')
120 | .append('p')
121 | .text('N = log10(calls)')
122 | }
123 |
124 | Component.prototype.setStateHandler$ = function() {
125 | this.stateHandler$ = Observable.merge(
126 | ..._.chain(this.valueDiv.nodes())
127 | .map(node => [
128 | Observable.fromEvent(node, 'mouseover')
129 | .map(() =>
130 | state => {
131 | let d = _.mapValues(d3.select(node).datum(), key => String(key))
132 | let update = {}
133 | if (!state[d.key][d.value]) {
134 | update =
135 | _.chain(state)
136 | .cloneDeep()
137 | .pick(d.key)
138 | .mapValues(obj => {
139 | obj[d.value] = {pinned: false}
140 | return obj
141 | })
142 | .value()
143 | }
144 | return Object.assign({}, state, update)
145 | }
146 | ),
147 | Observable.fromEvent(node, 'click')
148 | .map(() =>
149 | state => {
150 | let d = _.mapValues(d3.select(node).datum(), key => String(key))
151 | let update =
152 | _.chain(state)
153 | .cloneDeep()
154 | .pick(d.key)
155 | .mapValues(obj => {
156 | obj[d.value].pinned = !obj[d.value].pinned
157 | return obj
158 | // return Object.assign(obj[d.value], {pinned: !obj[d.value].pinned})
159 | })
160 | .value()
161 | return Object.assign({}, state, update)
162 | }
163 | ),
164 | Observable.fromEvent(node, 'mouseout')
165 | .map(() =>
166 | state => {
167 | let d = _.mapValues(d3.select(node).datum(), key => String(key))
168 | let update = {}
169 | if (!state[d.key][d.value].pinned) {
170 | update =
171 | _.chain(state)
172 | .cloneDeep()
173 | .pick(d.key)
174 | .mapValues(obj => _.omit(obj, d.value))
175 | .value()
176 | }
177 | return Object.assign({}, state, update)
178 | }
179 | )
180 | ])
181 | .flatten()
182 | .value()
183 | )
184 | // .share()
185 | }
186 |
187 | Component.prototype.getStateHandler$ = function() {
188 | return this.stateHandler$
189 | }
190 |
191 | Component.prototype.subscribeToState = function(state$) {
192 | state$.subscribe(state => {
193 | this.valueDiv.select('.value')
194 | .classed('pinned', d =>
195 | state[d.key][d.value]
196 | && state[d.key][d.value].pinned
197 | )
198 | .classed('hovered', d =>
199 | state[d.key][d.value]
200 | ? !state[d.key][d.value].pinned
201 | : false
202 | )
203 | })
204 | }
205 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # d3 benchmarks
2 |
3 | Some tests to support the discussion in [this d3-path issue](https://github.com/d3/d3-path/issues/10).
4 |
5 | ## Installation
6 |
7 | - `npm install`
8 | - `npm run build` (always run this after modifying files in `src/implementations`)
9 |
10 | ## Benches
11 |
12 | ### path
13 |
14 | This bench compares different implementations of d3's `path`, saving:
15 | - **execution time**,
16 | - **heap memory** used by the instance of `path` after running a command (`moveTo`, etc) `N` times.
17 |
18 | Run with: `npm run path`.
19 |
20 | #### Implementations of `d3.path()`
21 |
22 | - [current](https://github.com/d3/d3-path/blob/master/src/path.js): official version
23 | - [withFormat](https://github.com/mindrones/d3-benchmarks/blob/master/src/path/withFormat.js):
24 |
25 | - `pathCoerceFixed`: input value coercion to a number and truncation via `.toFixed()` (copied from [this PR](https://github.com/d3/d3-path/blob/fixed/src/path.js) and renamed `pathFixed` -> `pathCoerceFixed` as we use `pathFixed` with no input value coercion):
26 |
27 | ```js
28 | export function pathCoerceFixed(digits) {
29 | var path = new Path;
30 | (digits = +digits).toFixed(digits); // Validate digits.
31 | path._format = function(x) { return +x.toFixed(digits); };
32 | return path;
33 | }
34 | ```
35 |
36 | - `pathFixed`: similar to the previous one without input value coercion, truncation via `.toFixed()`:
37 |
38 | ```js
39 | export function pathFixed(digits) {
40 | var path = new Path;
41 | (digits = +digits).toFixed(digits); // Validate digits.
42 | path._format = function(x) { return x.toFixed(digits); };
43 | return path;
44 | }
45 | ```
46 |
47 | - `pathCoerceRound`: input value coercion to a number and truncation via [round](https://github.com/d3/d3-format/issues/32):
48 |
49 | ```js
50 | import {round} from '../utils/round'
51 | export function pathCoerceRound(digits) {
52 | var path = new Path;
53 | (digits = +digits).toFixed(digits); // Validate digits.
54 | path._format = function(x) { return round(+x, digits); };
55 | return path;
56 | }
57 | ```
58 |
59 | - `pathRound`: no input value coercion and truncation via same `round` as above:
60 |
61 | ```js
62 | export function pathRound(digits) {
63 | var path = new Path;
64 | digits = +digits).toFixed(digits); // Validate digits.
65 | path._format = function(x) { return round(x, digits); };
66 | return path;
67 | }
68 | ```
69 |
70 | - [withIf](https://github.com/mindrones/d3-benchmarks/blob/master/src/path/withIf.js): instead of using a `format()` function, use `if`s and round if we provided `digits`:
71 | ```js
72 | import {round as R} from '../utils/round'
73 |
74 | // ...
75 | moveTo: function(x, y) {
76 | if (this._d) {
77 | this._ += `M${R(this._x0 = this._x1 = x, this._d)},${R(this._y0 = this._y1 = y, this._d)}`;
78 | } else {
79 | this._ += `M${this._x0 = this._x1 = x},${this._y0 = this._y1 = y}`;
80 | }
81 | },
82 | ```
83 | This implementation duplicates code, so if the case we could test assigning values to temporary vars like this:
84 | ```js
85 | moveTo: function(x, y) {
86 | this._x0 = this._x1 = this._d ? R(x, this._d) : x
87 | this._y0 = this._y1 = this._d ? R(y, this._d) : y
88 | this._ += `M${this._x0},${this._y0}`;
89 | },
90 | ```
91 |
92 | #### Results
93 |
94 | Results are saved in `./data/path.json` as a list of objects like:
95 |
96 | ```js
97 | {
98 | "impl": "path.current.path",
99 | "digits": null,
100 | "command": "moveTo",
101 | "calls": 1,
102 | "heap": 46464.64,
103 | "duration": 3.170281801295085e-7
104 | }
105 | ```
106 |
107 | - `impl`: name of the implementation
108 | - `digits`: digits we passed to `path()`
109 | - `command`: executed path command ('moveTo', 'lineTo', etc)
110 | - `calls`: how many times we invoked the command on the path instance `p`
111 | - `heap`: heap memory used by the `p` instance after calling the `coommand` `calls` times, in bytes
112 | - `duration`: mean test execution time, in seconds
113 |
114 | **You can explore the results with this [interactive chart](https://mindrones.github.io/d3-benchmarks/path)**
115 |
116 | #### How to interpret results
117 |
118 | Ideally, for a given amount of calls of a certain command (i.e. '3 calls of `moveTo`' meaning `p.moveTo(N,N).moveTo(N,N).moveTo(N,N)`), we should expect this kind of results:
119 |
120 | 
121 |
122 | This is because calling a command with no digits always returns the same path string, the longest possible, no matter the chosen implementation, while passing values of `digits` lower than the maximum precision allowed by the platform (see [Number.EPSILON](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/EPSILON)) shortens the returned path string.
123 |
124 | For example, assuming `N = 10.1234567890123456` (16 digits):
125 |
126 | - `withFormat.path().moveTo(N,N) => "M10.1234567890123456,10.1234567890123456"`
127 | - `withFormat.pathRound(15).moveTo(N,N) => "M10.123456789012346,10.123456789012346"`
128 | - `withFormat.pathRound(10).moveTo(N,N) => "M10.1234567890,10.1234567890"`
129 | - `withFormat.pathRound(5).moveTo(N,N) => "M10.12346,10.12346"`
130 | - `withFormat.pathRound(0).moveTo(N,N) => "M10,10"`
131 |
132 | Hence, decreasing digits should lower the used heap as the instance of path has to store a shorter string, but rounding the input value should increase the execution time.
133 |
134 | Here's an example of we what get in practice:
135 |
136 | 
137 |
138 | #### Let's try this on a real visualization!
139 |
140 | This [interactive chart](https://mindrones.github.io/d3-benchmarks/path_client) shows a moving circle that we control via:
141 |
142 | - how many points the circle is made of: 1e2, 1e3, 1e4, 1e5;
143 | - which implementation of `line()` to be used: current official `d3.line()` or custom implementation using `withFormat.path()` (see above);
144 | - how many digits to be used to round numbers.
145 |
146 | At least of my machine:
147 | - below 1e5 points I see no difference in performance, no matter the implementation or number of digits;
148 | - using 1e5 points, not rounding would seem ~2x slower than rounding with 0 digits, so there's indeed an effect on performance.
149 |
150 | 
151 | 
152 | 
153 |
154 |
155 | ### round
156 |
157 | Compare two rounding functions and `.toFixed()`, also coercing the input (be it a number or a string) to a number, to check the coercion impact on speed.
158 |
159 | Tested implementations:
160 |
161 | - [mbostock's round](https://github.com/d3/d3-format/issues/32)
162 | - [MDN php-like round](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round#PHP-Like_rounding_Method)
163 |
164 | Run with: `npm run round`.
165 |
166 | Results are saved in `./data/rounding.json` as a list of objects like:
167 |
168 | ```js
169 | {
170 | "impl": "round",
171 | "transform": null,
172 | "digits": 0,
173 | "duration": 1.5478552534985366e-8
174 | },
175 | ```
176 |
177 | - `impl`: name of the rounding implementation
178 | - `transform`: input coercion
179 | - null: no coercion
180 | - 'CoerceNumber': `+N`
181 | - 'CoerceString': `+(N.toString())`
182 | - `digits`: digits we passed to the rounding function
183 | - `round(N, digits)`,
184 | - `roundMDN(N, digits)`,
185 | - `N.toFixed(digits)`
186 | - `duration`: mean test execution time, in seconds
187 |
--------------------------------------------------------------------------------
/src/bench/path.js:
--------------------------------------------------------------------------------
1 | /*
2 | node --expose-gc bench/path.js
3 | to be run as idle as possible:
4 | - charger connected
5 | - no wifi | sleep mode
6 | - no or limited amount of open apps | user activities
7 | */
8 |
9 | const fs = require('fs')
10 | const _ = require('lodash')
11 | const esprima = require('esprima')
12 | const escodegen = require('escodegen')
13 | const benchmark = require('benchmark');
14 | const bundle = require('../../build/bundle')
15 |
16 | const RESULTS_PATH = './data/path.json'
17 | const MAXEXP = 4 // test with 1, 10, 100, ..., 10^MAXEXP command invocations
18 | const MAXDIGITS = -Math.floor(Math.log10(Number.EPSILON)) // 16 on this machine
19 | const DIGITS_STEP = 5 // 16-1 = 15 -> digits 0, 5, 10, 15
20 | const commands = [
21 | 'moveTo',
22 | 'lineTo',
23 | 'quadraticCurveTo',
24 | 'rect',
25 | 'bezierCurveTo',
26 | 'arcTo',
27 | 'arc'
28 | ]
29 |
30 | // implementation / digits to be used as argument of path()
31 | const implementations = {
32 | 'path.current.path': [null],
33 | 'path.withIf.path': [null, MAXDIGITS],
34 | 'path.withFormat.path': [null],
35 | 'path.withFormat.pathRound': [MAXDIGITS],
36 | 'path.withFormat.pathCoerceRound': [MAXDIGITS],
37 | 'path.withFormat.pathFixed': [MAXDIGITS],
38 | 'path.withFormat.pathCoerceFixed': [MAXDIGITS]
39 | }
40 |
41 | // vars to accumulate benchmarks data
42 | let testData
43 | let results = []
44 |
45 | // these will change at each benchmark: we want them to be at module level
46 | // so that they won't be garbage collected until we explicitly call global.gc()
47 | // (which is why we run this bench with the flag `--expose-gc`)
48 | let path, p
49 |
50 | // setup the suite
51 | console.log(`Benchmarks setup...`)
52 | let suite = new benchmark.Suite('path')
53 | .on('start', function() {
54 | console.log(`Benchmarking...`)
55 | })
56 | .on('cycle', function(event) {
57 | console.log(`Done.`)
58 | })
59 | .on('complete', () => {
60 | fs.writeFile(RESULTS_PATH, JSON.stringify(results, null, 2), err => {
61 | if (err) {throw err}
62 | console.log('Saved results in:', RESULTS_PATH)
63 | })
64 | })
65 |
66 | // generate test functions and add the tests to the suite
67 | // this can take a while because some of them have 10^MAXEXP lines of code
68 | _.each(commands, command => {
69 | _.each(implementations, (maxDigits, impl) => {
70 | _.chain(maxDigits)
71 | .map(n => _.isNumber(n) ? _.range(0, n, DIGITS_STEP) : n)
72 | .flatten()
73 | .each(digits => {
74 | _.each(_.range(MAXEXP + 1), exp => {
75 | let calls = Math.pow(10, exp)
76 | let callsExp = calls.toExponential()
77 | let digitsString = _.isNull(digits) ? '' : digits
78 | suite.add(
79 | `${impl}(${digitsString}).${command}.${callsExp}`, // 'path.current.path(2).moveTo.5e2'
80 | exec(command, digits, calls), // exec(moveTo, 2, 5)
81 | {
82 | onStart: () => {
83 | console.log(`Executing ${impl}(${digitsString}).${command}.${callsExp}...`)
84 |
85 | path = _.get(bundle, impl)
86 | testData = {
87 | impl: impl,
88 | digits: digits,
89 | command: command,
90 | calls: calls,
91 | heap: []
92 | }
93 | p = null
94 | },
95 | onCycle: (event) => {
96 | // garbage collect everything we can, apart from `p`
97 | global.gc()
98 | let heapBeforeGC = process.memoryUsage().heapUsed
99 |
100 | // free `p`
101 | p = null
102 |
103 | // should garbage collect only `p`
104 | global.gc()
105 | let heapAfterGC = process.memoryUsage().heapUsed
106 | testData.heap.push(heapBeforeGC - heapAfterGC)
107 | },
108 | onComplete: (event) => {
109 | testData.heap = _.reduce(testData.heap,
110 | (sum, x) => sum + x
111 | ) / testData.heap.length
112 | testData.duration = event.target.times.period // secs
113 | results.push(testData)
114 | checkOutput(command, digits, calls)()
115 | },
116 | onError: (event) => {
117 | // FIXME log errors and save in file
118 | console.log('*************************************')
119 | console.log(event)
120 | console.log('*************************************')
121 | }
122 | }
123 | )
124 | })
125 | })
126 | .value()
127 | })
128 | })
129 |
130 | suite.run()
131 |
132 |
133 | function exec(command, digits, commandCalls) {
134 | let afuncAST = esprima.parse(`() => {}`).body[0]
135 |
136 | // make sure `p` is global, don't use `let p = ...`
137 | let initCode = _.isNull(digits) ? `p = path();` : `p = path(${digits});`
138 |
139 | let commandCode
140 | const N = 10.1234567890123456 // 16 digits as per MAXDIGITS on this machine
141 | if (_.includes([
142 | 'moveTo',
143 | 'lineTo',
144 | 'quadraticCurveTo',
145 | 'rect',
146 | 'bezierCurveTo'
147 | ], command)) {
148 | switch (command) {
149 | case 'moveTo':
150 | case 'lineTo':
151 | commandCode = `p.${command}(${N},${N});`
152 | break;
153 | case 'quadraticCurveTo':
154 | case 'rect':
155 | commandCode = `p.${command}(${N},${N},${N},${N});`
156 | break;
157 | case 'bezierCurveTo':
158 | commandCode = `p.bezierCurveTo(${N},${N},${N},${N},${N},${N},${N},${N})`
159 | break;
160 | default:
161 | break;
162 | }
163 | let commandAST = esprima.parse(commandCode).body[0];
164 | afuncAST.expression.body.body.push(
165 | esprima.parse(initCode),
166 | ..._.map(_.range(commandCalls), () => commandAST)
167 | )
168 | } else if (command === 'arcTo') {
169 | // arcs through points [0,0], [0.5,0.5], [1,0] and back
170 | // shifted of [delta, delta] to get numbers with digits
171 |
172 | const delta = 0.1234567890123456
173 | initCode += `p.moveTo(${1 + delta},${0 + delta});`
174 | let [x1, y1] = [0.5 + delta, 0.5 + delta]
175 | let y2 = 0 + delta
176 | let r = 1 / Math.sqrt(2)
177 | afuncAST.expression.body.body.push(
178 | esprima.parse(initCode),
179 | ..._.map(_.range(commandCalls), (n) => {
180 | // arcTo(x1, y1, x2, y2, radius)
181 | let x2 = n % 2 + delta
182 | commandCode = `p.arcTo(${x1},${y1},${x2},${y2},${r})`
183 | return esprima.parse(commandCode).body[0];
184 | })
185 | )
186 | } else if (command === 'arc') {
187 | // arc with center [1,-1] starting from [0,0] to [2,0] and back
188 | // shifted of [delta, delta] to get numbers with digits
189 |
190 | const delta = 0.1234567890123456
191 | let [x, y] = [1 + delta, -1 + delta]
192 | let r = Math.sqrt(2)
193 | afuncAST.expression.body.body.push(
194 | esprima.parse(initCode),
195 | ..._.map(_.range(commandCalls), (n) => {
196 | // arc(x, y, radius, startAngle, endAngle[, anticlockwise])
197 | let ccw = n % 2 === 1
198 | let a0 = Math.PI * (ccw ? 1 : 3) / 4
199 | let a1 = Math.PI * (ccw ? 3 : 1) / 4
200 | commandCode = `p.arc(${x},${y},${r},${a0},${a1},${ccw})`
201 | return esprima.parse(commandCode).body[0];
202 | })
203 | )
204 | }
205 | return eval(escodegen.generate(afuncAST))
206 | }
207 |
208 | // to check the result, append a console.log() to the exec() function
209 | function checkOutput(command, digits, commandCalls) {
210 | let afuncAST = esprima.parse(
211 | exec(command, digits, commandCalls).toString()
212 | ).body[0];
213 |
214 | if (commandCalls <= 10) {
215 | console.log('checkOutput...')
216 | let logAST = esprima.parse(`console.log(p.toString())`).body[0];
217 | afuncAST.expression.body.body.push(logAST)
218 | }
219 | return eval(escodegen.generate(afuncAST))
220 | }
221 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------