repo_id
stringlengths
21
96
file_path
stringlengths
31
155
content
stringlengths
1
92.9M
__index_level_0__
int64
0
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/interleaved-buffer/README.md
<img width="50" heigth="50" src="https://webpack.js.org/assets/icon-square-big.svg" /> ## Use deck.gl with Interleaved Binary Data ## Usage To install dependencies: ```bash npm install # or yarn ``` Commands: * `npm start` is the development target, to serves the app and hot reload. * `npm run build` is the production target, to create the final bundle and write to disk.
0
rapidsai_public_repos/node/modules/demo/deck/interleaved-buffer
rapidsai_public_repos/node/modules/demo/deck/interleaved-buffer/src/data.js
const data = [ { color: [180, 50, 0], position: [0, 0, 0] }, { color: [205, 150, 0], position: [0, 5, 0] }, { color: [75, 125, 0], position: [5, 5, 0] }, { color: [0, 205, 150], position: [5, 10, 0] }, { color: [0, 125, 180], position: [10, 10, 0] }, { color: [150, 0, 205], position: [10, 15, 0] }, { color: [205, 0, 150], position: [15, 15, 0] } ]; /* Interleaved buffer layout: | attribute | size | | ---------- | -------- | | color.R | 1 byte | | color.G | 1 byte | | color.B | 1 byte | | color.A | 1 byte | | position.x | 1 float | | position.y | 1 float | | position.z | 1 float | | ---------- | -------- | | total | 16 bytes | */ const bytesPerDatum = 16; const arraybuffer = new ArrayBuffer(data.length * bytesPerDatum); const view = new DataView(arraybuffer); for (let i = 0; i < data.length; i++) { const {color, position} = data[i]; const offset = i * bytesPerDatum; view.setUint8(offset + 0, color[0]); view.setUint8(offset + 1, color[1]); view.setUint8(offset + 2, color[2]); view.setUint8(offset + 3, 255); // WebGL expects little endian view.setFloat32(offset + 4, position[0], true); view.setFloat32(offset + 8, position[1], true); view.setFloat32(offset + 12, position[2], true); } export default new Float32Array(arraybuffer);
0
rapidsai_public_repos/node/modules/demo/deck/interleaved-buffer
rapidsai_public_repos/node/modules/demo/deck/interleaved-buffer/src/app.js
import {Deck, OrthographicView} from '@deck.gl/core'; import {ScatterplotLayer, PathLayer, SolidPolygonLayer} from '@deck.gl/layers'; import GL from '@luma.gl/constants'; import {Buffer} from '@luma.gl/core'; import data from './data'; /** DeckGL **/ const deck = new Deck({ container: 'container', views: new OrthographicView(), controller: true, initialViewState: { target: [6, 6, 0], zoom: 5 }, onWebGLInitialized }); console.log(data); function onWebGLInitialized(gl) { const buffer = new Buffer(gl, data); const positions = {buffer, type: GL.FLOAT, size: 3, offset: 4, stride: 16}; const colors = {buffer, type: GL.UNSIGNED_BYTE, size: 4, offset: 0, stride: 16}; const indices = new Uint16Array([0, 1, 2, 3, 4, 5, 4, 5, 6]); const layers = [ new SolidPolygonLayer({ id: 'polygons', data: { length: 2, startIndices: [0, 3], attributes: { indices, getPolygon: positions, getFillColor: colors } }, pickable: true, autoHighlight: true, _normalize: false, // this instructs SolidPolygonLayer to skip normalization and use the binary as is getWidth: 0.5 }), new PathLayer({ id: 'paths', data: { length: 2, startIndices: [0, 3], attributes: { // PathLayer expects padded positions (1 vertex to the left & 2 vertices to the right) // So it cannot share the same buffer with other layers without padding // TODO - handle in PathTesselator? getPath: {value: data, size: 3, offset: 4, stride: 16}, getColor: colors } }, pickable: true, autoHighlight: true, _pathType: 'open', // this instructs PathLayer to skip normalization and use the binary as is getWidth: 0.5 }), new ScatterplotLayer({ id: 'points', data: { length: 7, attributes: { getPosition: positions, getLineColor: colors } }, pickable: true, autoHighlight: true, stroked: true, filled: false, getRadius: 1, getLineWidth: 0.5 }) ]; deck.setProps({layers}); } /* global document */ document.body.style.margin = '0px';
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/heatmap/package.json
{ "private": true, "name": "@rapidsai/demo-deck-heatmap", "version": "22.12.2", "license": "Apache-2.0", "author": "NVIDIA, Inc. (https://nvidia.com/)", "maintainers": [ "Paul Taylor <paul.e.taylor@me.com>" ], "bin": "index.js", "scripts": { "start": "node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js", "watch": "find -type f | entr -c -d -r node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js" }, "dependencies": { "@deck.gl/aggregation-layers": "8.8.10", "@deck.gl/core": "8.8.10", "@deck.gl/react": "8.8.10", "@rapidsai/jsdom": "~22.12.2", "mjolnir.js": "2.7.1", "react": "17.0.2", "react-dom": "17.0.2", "react-map-gl": "7.0.19" }, "files": [ "app.jsx", "index.js", "package.json" ] }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/heatmap/index.js
#!/usr/bin/env node // Copyright (c) 2020, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. module.exports = (glfwOptions = { title: 'Heatmap Demo', transparent: false }) => { return require('@rapidsai/jsdom').RapidsJSDOM.fromReactComponent('./app.jsx', { glfwOptions, // Change cwd to the example dir so relative file paths are resolved module: {path: __dirname}, }); }; if (require.main === module) { module.exports().window.addEventListener('close', () => process.exit(0), {once: true}); }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/heatmap/README.md
This is a minimal standalone version of the HeatmapLayer example on [deck.gl](http://deck.gl) website. ### Usage Copy the content of this folder to your project. ```bash # install dependencies npm install # or yarn # bundle and serve the app with webpack npm start ``` ### Data format Sample data is stored in [deck.gl Example Data](https://github.com/visgl/deck.gl-data/tree/master/examples/screen-grid), showing Uber pickup locations in NYC. [Source](https://github.com/fivethirtyeight/uber-tlc-foil-response) To use your own data, check out the [documentation of HeatmapLayer](../../../docs/api-reference/aggregation-layers/heatmap-layer.md). ### Basemap The basemap in this example is provided by [CARTO free basemap service](https://carto.com/basemaps). To use an alternative base map solution, visit [this guide](https://deck.gl/docs/get-started/using-with-map#using-other-basemap-services)
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/heatmap/app.jsx
import { HeatmapLayer } from '@deck.gl/aggregation-layers'; import DeckGL from '@deck.gl/react'; import * as React from 'react'; import { StaticMap } from 'react-map-gl'; const DATA_URL = 'https://raw.githubusercontent.com/visgl/deck.gl-data/master/examples/screen-grid/uber-pickup-locations.json'; // eslint-disable-line const INITIAL_VIEW_STATE = { longitude: -73.75, latitude: 40.73, zoom: 9, maxZoom: 16, pitch: 0, bearing: 0 }; const MAP_STYLE = 'https://basemaps.cartocdn.com/gl/dark-matter-nolabels-gl-style/style.json'; export default function App({ data = DATA_URL, intensity = 1, threshold = 0.03, radiusPixels = 30, mapStyle = MAP_STYLE }) { const layers = [new HeatmapLayer({ data, id: 'heatmp-layer', pickable: false, getPosition: d => [d[0], d[1]], getWeight: d => d[2], radiusPixels, intensity, threshold })]; return ( <DeckGL initialViewState={INITIAL_VIEW_STATE} controller={true} layers={layers}> <StaticMap reuseMaps mapStyle={mapStyle} preventStyleDiffing={true} /> </DeckGL> ); }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/geojson/package.json
{ "private": true, "name": "@rapidsai/demo-deck-geojson", "version": "22.12.2", "license": "Apache-2.0", "author": "NVIDIA, Inc. (https://nvidia.com/)", "maintainers": [ "Paul Taylor <paul.e.taylor@me.com>" ], "bin": "index.js", "scripts": { "start": "node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js", "watch": "find -type f | entr -c -d -r node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js" }, "dependencies": { "@deck.gl/core": "8.8.10", "@deck.gl/layers": "8.8.10", "@deck.gl/react": "8.8.10", "@rapidsai/jsdom": "~22.12.2", "d3-scale": "2.2.2", "mjolnir.js": "2.7.1", "react": "17.0.2", "react-dom": "17.0.2", "react-map-gl": "7.0.19" }, "files": [ "app.jsx", "index.js", "package.json" ] }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/geojson/index.js
#!/usr/bin/env node // Copyright (c) 2020, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. module.exports = (glfwOptions = { title: 'GeoJson Demo', transparent: false }) => { return require('@rapidsai/jsdom').RapidsJSDOM.fromReactComponent('./app.jsx', { glfwOptions, // Change cwd to the example dir so relative file paths are resolved module: {path: __dirname}, }); }; if (require.main === module) { module.exports().window.addEventListener('close', () => process.exit(0), {once: true}); }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/geojson/README.md
This is a minimal standalone version of the GeoJsonLayer example on [deck.gl](http://deck.gl) website. ### Usage Copy the content of this folder to your project. To see the base map, you need a [Mapbox access token](https://docs.mapbox.com/help/how-mapbox-works/access-tokens/). You can either set an environment variable: ```bash export MapboxAccessToken=<mapbox_access_token> ``` Or set `MAPBOX_TOKEN` directly in `app.js`. Other options can be found at [using with Mapbox GL](../../../docs/get-started/using-with-mapbox-gl.md). ```bash # install dependencies npm install # or yarn # bundle and serve the app with webpack npm start ``` ### Data format Sample data is stored in [deck.gl Example Data](https://github.com/uber-common/deck.gl-data/tree/master/examples/geojson). To use your own data, checkout the [documentation of GeoJsonLayer](../../../docs/layers/geojson-layer.md).
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/geojson/app.jsx
import { _SunLight as SunLight, AmbientLight, LightingEffect } from '@deck.gl/core'; import { GeoJsonLayer, PolygonLayer } from '@deck.gl/layers'; import DeckGL from '@deck.gl/react'; import { scaleThreshold } from 'd3-scale'; import * as React from 'react'; import { Component } from 'react'; import { render } from 'react-dom'; import { StaticMap } from 'react-map-gl'; // Set your mapbox token here const MAPBOX_TOKEN = 'pk.eyJ1Ijoid21qcGlsbG93IiwiYSI6ImNrN2JldzdpbDA2Ym0zZXFzZ3oydXN2ajIifQ.qPOZDsyYgMMUhxEKrvHzRA'; // eslint-disable-line // Source data GeoJSON const DATA_URL = 'https://raw.githubusercontent.com/uber-common/deck.gl-data/master/examples/geojson/vancouver-blocks.json'; // eslint-disable-line export const COLOR_SCALE = scaleThreshold() .domain([-0.6, -0.45, -0.3, -0.15, 0, 0.15, 0.3, 0.45, 0.6, 0.75, 0.9, 1.05, 1.2]) .range([ [65, 182, 196], [127, 205, 187], [199, 233, 180], [237, 248, 177], // zero [255, 255, 204], [255, 237, 160], [254, 217, 118], [254, 178, 76], [253, 141, 60], [252, 78, 42], [227, 26, 28], [189, 0, 38], [128, 0, 38] ]); const INITIAL_VIEW_STATE = { latitude: 49.254, longitude: -123.13, zoom: 11, maxZoom: 16, pitch: 45, bearing: 0 }; const ambientLight = new AmbientLight({ color: [255, 255, 255], intensity: 1.0 }); const dirLight = new SunLight( { timestamp: Date.UTC(2019, 7, 1, 22), color: [255, 255, 255], intensity: 1.0, _shadow: true }); const landCover = [[[-123.0, 49.196], [-123.0, 49.324], [-123.306, 49.324], [-123.306, 49.196]]]; export default class App extends Component { constructor(props) { super(props); this.state = { hoveredObject: null }; this._onHover = this._onHover.bind(this); this._renderTooltip = this._renderTooltip.bind(this); const lightingEffect = new LightingEffect({ ambientLight, dirLight }); lightingEffect.shadowColor = [0, 0, 0, 0.5]; this._effects = [lightingEffect]; } _onHover({ x, y, object }) { this.setState({ x, y, hoveredObject: object }); } _renderLayers() { const { data = DATA_URL } = this.props; return [ // only needed when using shadows - a plane for shadows to drop on new PolygonLayer({ id: 'ground', data: landCover, stroked: false, getPolygon: f => f, getFillColor: [0, 0, 0, 0] }), new GeoJsonLayer({ id: 'geojson', data, opacity: 0.8, stroked: false, filled: true, extruded: true, wireframe: true, getElevation: f => Math.sqrt(f.properties.valuePerSqm) * 10, getFillColor: f => COLOR_SCALE(f.properties.growth), getLineColor: [255, 255, 255], pickable: true, onHover: this._onHover }) ]; } _renderTooltip() { const { x, y, hoveredObject } = this.state; return (hoveredObject && (<div className='tooltip' style={{ top: y, left: x }}><div> <b>Average Property Value</b> </div><div> <div>$ {hoveredObject.properties.valuePerParcel} / parcel</div > <div>$ {hoveredObject.properties.valuePerSqm} / m<sup>2</sup > </div> </div><div><b>Growth</b> </div> <div>{Math.round(hoveredObject.properties.growth * 100)} % </div> </div>)); } render() { const { mapStyle = 'https://basemaps.cartocdn.com/gl/dark-matter-nolabels-gl-style/style.json' } = this.props; return ( <DeckGL layers={this._renderLayers()} effects={this._effects} initialViewState={INITIAL_VIEW_STATE} controller={true}> <StaticMap reuseMaps mapStyle={mapStyle} preventStyleDiffing={true} mapboxApiAccessToken={MAPBOX_TOKEN} /> {this._renderTooltip} </DeckGL> ); } } export function renderToDOM(container) { render(<App />, container); }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/mesh/package.json
{ "private": true, "name": "@rapidsai/demo-deck-mesh-layer-example", "version": "22.12.2", "license": "Apache-2.0", "author": "NVIDIA, Inc. (https://nvidia.com/)", "maintainers": [ "Paul Taylor <paul.e.taylor@me.com>" ], "bin": "index.js", "scripts": { "start": "node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js", "watch": "find -type f | entr -c -d -r node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js" }, "dependencies": { "@deck.gl/core": "8.8.10", "@deck.gl/layers": "8.8.10", "@deck.gl/mesh-layers": "8.8.10", "@deck.gl/react": "8.8.10", "@loaders.gl/core": "3.2.9", "@loaders.gl/obj": "3.2.9", "@rapidsai/jsdom": "~22.12.2", "mjolnir.js": "2.7.1", "react": "17.0.2", "react-dom": "17.0.2" }, "files": [ "app.js", "index.js", "package.json" ] }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/mesh/index.js
#!/usr/bin/env node // Copyright (c) 2020, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. module.exports = (glfwOptions = { title: 'Mesh Demo', transparent: false }) => { return require('@rapidsai/jsdom').RapidsJSDOM.fromReactComponent('./app.jsx', { glfwOptions, // Change cwd to the example dir so relative file paths are resolved module: {path: __dirname}, }); }; if (require.main === module) { module.exports().window.addEventListener('close', () => process.exit(0), {once: true}); }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/mesh/README.md
This is a minimal example of [deck.gl](http://deck.gl)'s SimpleMeshLayer. ### Usage Copy the content of this folder to your project. ```bash # install dependencies npm install # or yarn # bundle and serve the app with webpack npm start ``` ### Data format This example generates an arbitrary set of data points. To use your own data, checkout the [documentation of SimpleMeshLayer](../../../docs/layers/simple-mesh-layer.md).
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/mesh/app.jsx
import * as React from 'react' import { PureComponent } from 'react'; import { render } from 'react-dom'; import DeckGL from '@deck.gl/react'; import { COORDINATE_SYSTEM, OrbitView, DirectionalLight, LightingEffect, AmbientLight } from '@deck.gl/core'; import { SolidPolygonLayer } from '@deck.gl/layers'; import { SimpleMeshLayer } from '@deck.gl/mesh-layers'; import { OBJLoader } from '@loaders.gl/obj'; import { registerLoaders } from '@loaders.gl/core'; // Add the loaders that handle your mesh format here registerLoaders([OBJLoader]); const MESH_URL = 'https://raw.githubusercontent.com/uber-common/deck.gl-data/master/examples/mesh/minicooper.obj'; const INITIAL_VIEW_STATE = { target: [0, 0, 0], rotationX: 0, rotationOrbit: 0, orbitAxis: 'Y', fov: 30, zoom: 0 }; const SAMPLE_DATA = (([xCount, yCount], spacing) => { const data = []; for (let x = 0; x < xCount; x++) { for (let y = 0; y < yCount; y++) { data.push({ position: [(x - (xCount - 1) / 2) * spacing, (y - (yCount - 1) / 2) * spacing], color: [(x / (xCount - 1)) * 255, 128, (y / (yCount - 1)) * 255], orientation: [(x / (xCount - 1)) * 60 - 30, 0, -90] }); } } return data; })([10, 10], 120); const ambientLight = new AmbientLight({ color: [255, 255, 255], intensity: 1.0 }); const dirLight = new DirectionalLight({ color: [255, 255, 255], intensity: 1.0, direction: [-10, -2, -15], _shadow: true }); const lightingEffect = new LightingEffect({ ambientLight, dirLight }); const background = [ [[-1000.0, -1000.0, -40], [1000.0, -1000.0, -40], [1000.0, 1000.0, -40], [-1000.0, 1000.0, -40]] ]; export default class App extends PureComponent { render() { const layers = [ new SimpleMeshLayer({ id: 'mini-coopers', data: SAMPLE_DATA, mesh: MESH_URL, coordinateSystem: COORDINATE_SYSTEM.CARTESIAN, getPosition: d => d.position, getColor: d => d.color, getOrientation: d => d.orientation }), // only needed when using shadows - a plane for shadows to drop on new SolidPolygonLayer({ id: 'background', data: background, extruded: false, coordinateSystem: COORDINATE_SYSTEM.CARTESIAN, getPolygon: f => f, getFillColor: [0, 0, 0, 0] }) ]; return ( <DeckGL views={ new OrbitView({ near: 0.1, far: 2 }) } initialViewState={INITIAL_VIEW_STATE} controller={true} layers={layers} effects={[lightingEffect]} /> ); } } export function renderToDOM(container) { render(<App />, container); }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/plot/package.json
{ "private": true, "name": "@rapidsai/demo-deck-plot", "version": "22.12.2", "license": "Apache-2.0", "author": "NVIDIA, Inc. (https://nvidia.com/)", "maintainers": [ "Paul Taylor <paul.e.taylor@me.com>" ], "bin": "index.js", "scripts": { "start": "node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js", "watch": "find -type f | entr -c -d -r node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js" }, "dependencies": { "@deck.gl/core": "8.8.10", "@deck.gl/react": "8.8.10", "@rapidsai/jsdom": "~22.12.2", "d3-scale": "2.2.2", "mjolnir.js": "2.7.1", "react": "17.0.2", "react-dom": "17.0.2" }, "files": [ "app.js", "index.js", "plot-layer", "package.json" ] }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/plot/index.js
#!/usr/bin/env node // Copyright (c) 2020, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. module.exports = (glfwOptions = { title: 'Plot Demo', transparent: false }) => { return require('@rapidsai/jsdom').RapidsJSDOM.fromReactComponent('./app.jsx', { glfwOptions, // Change cwd to the example dir so relative file paths are resolved module: {path: __dirname}, }); }; if (require.main === module) { module.exports().window.addEventListener('close', () => process.exit(0), {once: true}); }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/plot/README.md
This is a minimal standalone version of the Graph Explorer example on [deck.gl](http://deck.gl) website. ### Usage Copy the content of this folder to your project. ```bash # install dependencies npm install # or yarn # bundle and serve the app with webpack npm start ``` ### Data format Sample data is stored in the `data` folder. To use your own data, checkout the [documentation of PlotLayer](./plot-layer/README.md).
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/plot/app.jsx
import { OrbitView } from '@deck.gl/core'; import DeckGL from '@deck.gl/react'; import { scaleLinear } from 'd3-scale'; import * as React from 'react'; import { Component } from 'react'; import { render } from 'react-dom'; import PlotLayer from './plot-layer'; const EQUATION = (x, y) => (Math.sin(x * x + y * y) * x) / Math.PI; const INITIAL_VIEW_STATE = { target: [0.5, 0.5, 0.5], orbitAxis: 'Y', rotationX: 30, rotationOrbit: -30, /* global window */ zoom: typeof window !== `undefined` ? Math.log2(window.innerHeight / 3) : 1 // fit 3x3x3 box in current viewport }; function getScale({ min, max }) { return scaleLinear().domain([min, max]).range([0, 1]); } export default class App extends Component { constructor(props) { super(props); this.state = { hoverInfo: null }; this._onHover = this._onHover.bind(this); this._renderTooltip = this._renderTooltip.bind(this); } _onHover(info) { const hoverInfo = info.sample ? info : null; if (hoverInfo !== this.state.hoverInfo) { this.setState({ hoverInfo }); } } _renderTooltip() { const { hoverInfo } = this.state; return ( hoverInfo && ( <div className='tooltip' style={{ left: hoverInfo.x, top: hoverInfo.y }}> {hoverInfo.sample.map(x => x.toFixed(3)).join(', ')} </div> ) ); } render() { const { resolution = 200, showAxis = true, equation = EQUATION } = this.props; const layers = [ equation && resolution && new PlotLayer({ getPosition: (u, v) => { const x = (u - 1 / 2) * Math.PI * 2; const y = (v - 1 / 2) * Math.PI * 2; return [x, y, equation(x, y)]; }, getColor: (x, y, z) => [40, z * 128 + 128, 160], getXScale: getScale, getYScale: getScale, getZScale: getScale, uCount: resolution, vCount: resolution, drawAxes: showAxis, axesPadding: 0.25, axesColor: [0, 0, 0, 128], pickable: true, onHover: this._onHover, updateTriggers: { getPosition: equation } }) ]; return ( <DeckGL layers={layers} views={new OrbitView()} initialViewState={INITIAL_VIEW_STATE} controller={true} > {this._renderTooltip} </DeckGL> ); } } export function renderToDOM(container) { render(<App />, container); }
0
rapidsai_public_repos/node/modules/demo/deck/plot
rapidsai_public_repos/node/modules/demo/deck/plot/plot-layer/index.js
export {default as AxesLayer} from './axes-layer'; export {default as SurfaceLayer} from './surface-layer'; export {default} from './plot-layer';
0
rapidsai_public_repos/node/modules/demo/deck/plot
rapidsai_public_repos/node/modules/demo/deck/plot/plot-layer/axes-fragment.glsl.js
// Copyright (c) 2015 - 2017 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. export default `\ #define SHADER_NAME graph-layer-fragment-shader precision highp float; varying vec4 vColor; varying float shouldDiscard; void main(void) { if (shouldDiscard > 0.0) { discard; } gl_FragColor = vColor; } `;
0
rapidsai_public_repos/node/modules/demo/deck/plot
rapidsai_public_repos/node/modules/demo/deck/plot/plot-layer/label-fragment.glsl.js
// Copyright (c) 2015 - 2017 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. export default `\ #define SHADER_NAME graph-layer-fragment-shader precision highp float; uniform sampler2D labelTexture; varying vec2 vTexCoords; varying float shouldDiscard; void main(void) { if (shouldDiscard > 0.0) { discard; } vec4 color = texture2D(labelTexture, vTexCoords); if (color.a == 0.0) { discard; } gl_FragColor = color; } `;
0
rapidsai_public_repos/node/modules/demo/deck/plot
rapidsai_public_repos/node/modules/demo/deck/plot/plot-layer/README.md
# Plot Layer This layer plots a math equation in 3d space. Each sample point on the 3d surface is represented by `x, y, z` values and color. It can also render axes and labels around the surface. (requires `d3-scale` module) import PlotLayer from './plot-layer'; Inherits from all [Base Layer](/docs/layers/base-layer.md) properties. ##### `getPosition` (Function, optional) - Default: `(u, v) => [0, 0, 0]` Called to get the `[x, y, z]` value from a `(u, v)` pair. Arguments: - `u` (Number) - a value between `[0, 1]` - `v` (Number) - a value between `[0, 1]` ##### `getColor` (Function, optional) - Default: `(x, y, z) => [0, 0, 0, 255]` Called for each `(x, y, z)` triplet to retreive surface color. Returns an array in the form of `[r, g, b, a]`. If the alpha component is not supplied, it is default to `255`. ##### `getXScale` (Function, optional) - Default: `({min, max}) => d3.scaleLinear()` Called to retreive a [d3 scale](https://github.com/d3/d3-scale/blob/master/README.md) for x values. Default to identity. Arguments: - `context` (Object) + `context.min` (Number) - lower bounds of x values + `context.max` (Number) - upper bounds of x values ##### `getYScale` (Function, optional) - Default: `({min, max}) => d3.scaleLinear()` Called to retreive a [d3 scale](https://github.com/d3/d3-scale/blob/master/README.md) for y values. Default to identity. Arguments: - `context` (Object) + `context.min` (Number) - lower bounds of y values + `context.max` (Number) - upper bounds of y values ##### `getZScale` (Function, optional) - Default: `({min, max}) => d3.scaleLinear()` Called to retreive a [d3 scale](https://github.com/d3/d3-scale/blob/master/README.md) for z values. Default to identity. Arguments: - `context` (Object) + `context.min` (Number) - lower bounds of z values + `context.max` (Number) - upper bounds of z values ##### `uCount` (Number, optional) - Default: `100` Number of points to sample `u` in the `[0, 1]` range. ##### `vCount` (Number, optional) - Default: `100` Number of points to sample `v` in the `[0, 1]` range. ##### `lightStrength` (Number, optional) - Default: `0.1` Intensity of the front-lit effect for the 3d surface. ##### `drawAxes` (Bool, optional) - Default: `true` Whether to draw axis grids and labels. ##### `fontSize` (Number, optional) - Default: `12` Font size of the labels. ##### `xTicks` (Number | [Number], optional) - Default: `6` Either number of ticks on x axis, or an array of tick values. ##### `yTicks` (Number | [Number], optional) - Default: `6` Either number of ticks on y axis, or an array of tick values. ##### `zTicks` (Number | [Number], optional) - Default: `6` Either number of ticks on z axis, or an array of tick values. ##### `xTickFormat` (Function, optional) - Default: `value => value.toFixed(2)` Format a tick value on x axis to text string. ##### `yTickFormat` (Function, optional) - Default: `value => value.toFixed(2)` Format a tick value on y axis to text string. ##### `zTickFormat` (Function, optional) - Default: `value => value.toFixed(2)` Format a tick value on z axis to text string. ##### `xTitle` (String, optional) - Default: `x` X axis title string. ##### `yTitle` (String, optional) - Default: `y` Y axis title string. ##### `zTitle` (String, optional) - Default: `z` Z axis title string. ##### `axesPadding` (Number, optional) - Default: `0` Amount that grids should setback from the bounding box. Relative to the size of the bounding box. ##### `axesColor` (Array, optional) - Default: `[0, 0, 0, 255]` Color to draw the grids with, in `[r, g, b, a]`. ##### `axesTitles` (Array, optional) - Default: `['x', 'z', 'y']` Strings to draw next to each axis as their titles, note that the second element is the axis that points upwards.
0
rapidsai_public_repos/node/modules/demo/deck/plot
rapidsai_public_repos/node/modules/demo/deck/plot/plot-layer/grid-vertex.glsl.js
// Copyright (c) 2015 - 2017 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. export default `\ #define SHADER_NAME graph-layer-axis-vertex-shader attribute vec3 positions; attribute vec3 normals; attribute vec2 instancePositions; attribute vec3 instanceNormals; attribute float instanceIsTitle; uniform vec3 gridDims; uniform vec3 gridCenter; uniform float gridOffset; uniform vec4 strokeColor; varying vec4 vColor; varying float shouldDiscard; // determines if the grid line is behind or in front of the center float frontFacing(vec3 v) { vec4 v_clipspace = project_uViewProjectionMatrix * project_uModelMatrix * vec4(v, 0.0); return step(v_clipspace.z, 0.0); } void main(void) { // rotated rectangle to align with slice: // for each x tick, draw rectangle on yz plane // for each y tick, draw rectangle on zx plane // for each z tick, draw rectangle on xy plane // offset of each corner of the rectangle from tick on axis vec3 gridVertexOffset = mat3( vec3(positions.z, positions.xy), vec3(positions.yz, positions.x), positions ) * instanceNormals; // normal of each edge of the rectangle from tick on axis vec3 gridLineNormal = mat3( vec3(normals.z, normals.xy), vec3(normals.yz, normals.x), normals ) * instanceNormals; // do not draw grid line in front of the graph shouldDiscard = frontFacing(gridLineNormal) + instanceIsTitle; vec3 position_modelspace = vec3(instancePositions.x) * instanceNormals + gridVertexOffset * gridDims / 2.0 + gridCenter * abs(gridVertexOffset); // apply offsets position_modelspace += gridOffset * gridLineNormal; vec3 position_commonspace = project_position(position_modelspace); gl_Position = project_common_position_to_clipspace(vec4(position_commonspace, 1.0)); vColor = strokeColor / 255.0; } `;
0
rapidsai_public_repos/node/modules/demo/deck/plot
rapidsai_public_repos/node/modules/demo/deck/plot/plot-layer/utils.js
/* global document */ import GL from '@luma.gl/constants'; import {Texture2D} from '@luma.gl/core'; // helper for textMatrixToTexture function setTextStyle(ctx, fontSize) { ctx.font = `${fontSize}px Helvetica,Arial,sans-serif`; ctx.fillStyle = '#000'; ctx.textBaseline = 'top'; ctx.textAlign = 'center'; } /* * renders a matrix of text labels to texture2D. * @param {WebGLRenderingContext} glContext * @param {[[String]]} data: text to render, in array of columns (array of strings) * @param {Number} fontSize: size to render with * @returns {object} {texture, columnWidths} */ export function textMatrixToTexture(glContext, data, fontSize = 48) { const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); setTextStyle(ctx, fontSize); // measure texts const columnWidths = data.map(column => { return column.reduce((acc, obj) => { const w = ctx.measureText(obj.text).width; return Math.max(acc, Math.ceil(w)); }, 0); }); const canvasWidth = columnWidths.reduce((x, w) => x + w, 0); const canvasHeight = data.reduce( (h, column) => Math.max(h, Math.ceil(column.length * fontSize)), 0 ); if (canvasWidth === 0 || canvasHeight === 0) { // empty canvas willl cause error in Texture2D return null; } canvas.width = canvasWidth; canvas.height = canvasHeight; // changing canvas size will reset context setTextStyle(ctx, fontSize); /* * +----------+----------+----------+ * | col0:0 | col1:0 | col2:0 | * +----------+----------+----------+ * | col0:1 | col1:1 | col2:1 | * +----------+----------+----------+ * | ... | ... | ... | */ let x = 0; data.forEach((column, colIndex) => { x += columnWidths[colIndex] / 2; column.forEach((obj, i) => { ctx.fillText(obj.text, x, i * fontSize); }); x += columnWidths[colIndex] / 2; }); return { columnWidths, texture: new Texture2D(glContext, { pixels: canvas, [GL.TEXTURE_MAG_FILTER]: GL.LINEAR }) }; }
0
rapidsai_public_repos/node/modules/demo/deck/plot
rapidsai_public_repos/node/modules/demo/deck/plot/plot-layer/axes-layer.js
import {Layer} from '@deck.gl/core'; import GL from '@luma.gl/constants'; import {Model, Geometry} from '@luma.gl/core'; import {textMatrixToTexture} from './utils'; import fragmentShader from './axes-fragment.glsl'; import gridVertex from './grid-vertex.glsl'; import labelVertex from './label-vertex.glsl'; import labelFragment from './label-fragment.glsl'; /* Constants */ const DEFAULT_FONT_SIZE = 48; const DEFAULT_TICK_COUNT = 6; const DEFAULT_TICK_FORMAT = x => x.toFixed(2); const defaultProps = { data: [], fontSize: 12, xScale: null, yScale: null, zScale: null, xTicks: DEFAULT_TICK_COUNT, yTicks: DEFAULT_TICK_COUNT, zTicks: DEFAULT_TICK_COUNT, xTickFormat: DEFAULT_TICK_FORMAT, yTickFormat: DEFAULT_TICK_FORMAT, zTickFormat: DEFAULT_TICK_FORMAT, padding: 0, color: [0, 0, 0, 255], xTitle: 'x', yTitle: 'y', zTitle: 'z' }; /* Utils */ function flatten(arrayOfArrays) { const flatArray = arrayOfArrays.reduce((acc, arr) => acc.concat(arr), []); if (Array.isArray(flatArray[0])) { return flatten(flatArray); } return flatArray; } function getTicks(props) { const {axis} = props; let ticks = props[`${axis}Ticks`]; const scale = props[`${axis}Scale`]; const tickFormat = props[`${axis}TickFormat`]; if (!Array.isArray(ticks)) { ticks = scale.ticks(ticks); } const titleTick = { value: props[`${axis}Title`], position: (scale.range()[0] + scale.range()[1]) / 2, text: props[`${axis}Title`] }; return [ ...ticks.map(t => ({ value: t, position: scale(t), text: tickFormat(t, axis) })), titleTick ]; } /* * @classdesc * A layer that plots a surface based on a z=f(x,y) equation. * * @class * @param {Object} [props] * @param {Integer} [props.ticksCount] - number of ticks along each axis, see https://github.com/d3/d3-axis/blob/master/README.md#axis_ticks * @param {Number} [props.padding] - amount to set back grids from the plot, relative to the size of the bounding box * @param {d3.scale} [props.xScale] - a d3 scale for the x axis * @param {d3.scale} [props.yScale] - a d3 scale for the y axis * @param {d3.scale} [props.zScale] - a d3 scale for the z axis * @param {Number | [Number]} [props.xTicks] - either tick counts or an array of tick values * @param {Number | [Number]} [props.yTicks] - either tick counts or an array of tick values * @param {Number | [Number]} [props.zTicks] - either tick counts or an array of tick values * @param {Function} [props.xTickFormat] - returns a string from value * @param {Function} [props.yTickFormat] - returns a string from value * @param {Function} [props.zTickFormat] - returns a string from value * @param {String} [props.xTitle] - x axis title * @param {String} [props.yTitle] - y axis title * @param {String} [props.zTitle] - z axis title * @param {Number} [props.fontSize] - size of the labels * @param {Array} [props.color] - color of the gridlines, in [r,g,b,a] */ export default class AxesLayer extends Layer { initializeState() { const {gl} = this.context; const attributeManager = this.getAttributeManager(); attributeManager.addInstanced({ instancePositions: {size: 2, update: this.calculateInstancePositions, noAlloc: true}, instanceNormals: {size: 3, update: this.calculateInstanceNormals, noAlloc: true}, instanceIsTitle: {size: 1, update: this.calculateInstanceIsTitle, noAlloc: true} }); this.setState( Object.assign( { numInstances: 0, labels: null }, this._getModels(gl) ) ); } updateState({oldProps, props, changeFlags}) { const attributeManager = this.getAttributeManager(); if ( oldProps.xScale !== props.xScale || oldProps.yScale !== props.yScale || oldProps.zScale !== props.zScale || oldProps.xTicks !== props.xTicks || oldProps.yTicks !== props.yTicks || oldProps.zTicks !== props.zTicks || oldProps.xTickFormat !== props.xTickFormat || oldProps.yTickFormat !== props.yTickFormat || oldProps.zTickFormat !== props.zTickFormat ) { const {xScale, yScale, zScale} = props; const ticks = [ getTicks({...props, axis: 'x'}), getTicks({...props, axis: 'z'}), getTicks({...props, axis: 'y'}) ]; const xRange = xScale.range(); const yRange = yScale.range(); const zRange = zScale.range(); this.setState({ ticks, labelTexture: this.renderLabelTexture(ticks), gridDims: [xRange[1] - xRange[0], zRange[1] - zRange[0], yRange[1] - yRange[0]], gridCenter: [ (xRange[0] + xRange[1]) / 2, (zRange[0] + zRange[1]) / 2, (yRange[0] + yRange[1]) / 2 ] }); attributeManager.invalidateAll(); } } draw({uniforms}) { const {gridDims, gridCenter, modelsByName, labelTexture, numInstances} = this.state; const {fontSize, color, padding} = this.props; if (labelTexture) { const baseUniforms = { fontSize, gridDims, gridCenter, gridOffset: padding, strokeColor: color }; modelsByName.grids.setInstanceCount(numInstances); modelsByName.labels.setInstanceCount(numInstances); modelsByName.grids.setUniforms(Object.assign({}, uniforms, baseUniforms)).draw(); modelsByName.labels .setUniforms(Object.assign({}, uniforms, baseUniforms, labelTexture)) .draw(); } } _getModels(gl) { /* grids: * for each x tick, draw rectangle on yz plane around the bounding box. * for each y tick, draw rectangle on zx plane around the bounding box. * for each z tick, draw rectangle on xy plane around the bounding box. * show/hide is toggled by the vertex shader */ /* * rectangles are defined in 2d and rotated in the vertex shader * * (-1,1) (1,1) * +-----------+ * | | * | | * | | * | | * +-----------+ * (-1,-1) (1,-1) */ // offset of each corner const gridPositions = [ // left edge -1, -1, 0, -1, 1, 0, // top edge -1, 1, 0, 1, 1, 0, // right edge 1, 1, 0, 1, -1, 0, // bottom edge 1, -1, 0, -1, -1, 0 ]; // normal of each edge const gridNormals = [ // left edge -1, 0, 0, -1, 0, 0, // top edge 0, 1, 0, 0, 1, 0, // right edge 1, 0, 0, 1, 0, 0, // bottom edge 0, -1, 0, 0, -1, 0 ]; const grids = new Model(gl, { id: `${this.props.id}-grids`, vs: gridVertex, fs: fragmentShader, geometry: new Geometry({ drawMode: GL.LINES, attributes: { positions: new Float32Array(gridPositions), normals: new Float32Array(gridNormals) }, vertexCount: gridPositions.length / 3 }), isInstanced: true }); /* labels * one label is placed at each end of every grid line * show/hide is toggled by the vertex shader */ let labelTexCoords = []; let labelPositions = []; let labelNormals = []; let labelIndices = []; for (let i = 0; i < 8; i++) { /* * each label is rendered as a rectangle * 0 2 * +--.+ * | / | * +'--+ * 1 3 */ labelTexCoords = labelTexCoords.concat([0, 0, 0, 1, 1, 0, 1, 1]); labelIndices = labelIndices.concat([ i * 4 + 0, i * 4 + 1, i * 4 + 2, i * 4 + 2, i * 4 + 1, i * 4 + 3 ]); // all four vertices of this label's rectangle is anchored at the same grid endpoint for (let j = 0; j < 4; j++) { labelPositions = labelPositions.concat(gridPositions.slice(i * 3, i * 3 + 3)); labelNormals = labelNormals.concat(gridNormals.slice(i * 3, i * 3 + 3)); } } const labels = new Model(gl, { id: `${this.props.id}-labels`, vs: labelVertex, fs: labelFragment, geometry: new Geometry({ drawMode: GL.TRIANGLES, attributes: { indices: new Uint16Array(labelIndices), positions: new Float32Array(labelPositions), texCoords: {size: 2, value: new Float32Array(labelTexCoords)}, normals: new Float32Array(labelNormals) } }), isInstanced: true }); return { models: [grids, labels].filter(Boolean), modelsByName: {grids, labels} }; } calculateInstancePositions(attribute) { const {ticks} = this.state; const positions = ticks.map(axisTicks => axisTicks.map((t, i) => [t.position, i])); const value = new Float32Array(flatten(positions)); attribute.value = value; this.setState({numInstances: value.length / attribute.size}); } calculateInstanceNormals(attribute) { const { ticks: [xTicks, zTicks, yTicks] } = this.state; const normals = [ xTicks.map(t => [1, 0, 0]), zTicks.map(t => [0, 1, 0]), yTicks.map(t => [0, 0, 1]) ]; attribute.value = new Float32Array(flatten(normals)); } calculateInstanceIsTitle(attribute) { const {ticks} = this.state; const isTitle = ticks.map(axisTicks => { const ticksCount = axisTicks.length - 1; return axisTicks.map((t, i) => (i < ticksCount ? 0 : 1)); }); attribute.value = new Float32Array(flatten(isTitle)); } renderLabelTexture(ticks) { if (this.state.labels) { this.state.labels.labelTexture.delete(); } // attach a 2d texture of all the label texts const textureInfo = textMatrixToTexture(this.context.gl, ticks, DEFAULT_FONT_SIZE); if (textureInfo) { // success const {columnWidths, texture} = textureInfo; return { labelHeight: DEFAULT_FONT_SIZE, labelWidths: columnWidths, labelTextureDim: [texture.width, texture.height], labelTexture: texture }; } return null; } } AxesLayer.layerName = 'AxesLayer'; AxesLayer.defaultProps = defaultProps;
0
rapidsai_public_repos/node/modules/demo/deck/plot
rapidsai_public_repos/node/modules/demo/deck/plot/plot-layer/plot-layer.js
import {CompositeLayer, COORDINATE_SYSTEM} from '@deck.gl/core'; import {scaleLinear} from 'd3-scale'; import AxesLayer from './axes-layer'; import SurfaceLayer from './surface-layer'; const DEFAULT_GET_SCALE = {type: 'function', value: () => scaleLinear()}; const DEFAULT_TICK_FORMAT = {type: 'function', value: x => x.toFixed(2)}; const DEFAULT_TICK_COUNT = 6; const DEFAULT_COLOR = [0, 0, 0, 255]; const defaultProps = { // SurfaceLayer props getPosition: {type: 'accessor', value: (u, v) => [0, 0, 0]}, getColor: {type: 'accessor', value: (x, y, z) => DEFAULT_COLOR}, getXScale: DEFAULT_GET_SCALE, getYScale: DEFAULT_GET_SCALE, getZScale: DEFAULT_GET_SCALE, uCount: 100, vCount: 100, lightStrength: 0.1, // AxesLayer props drawAxes: true, fontSize: 12, xTicks: DEFAULT_TICK_COUNT, yTicks: DEFAULT_TICK_COUNT, zTicks: DEFAULT_TICK_COUNT, xTickFormat: DEFAULT_TICK_FORMAT, yTickFormat: DEFAULT_TICK_FORMAT, zTickFormat: DEFAULT_TICK_FORMAT, xTitle: 'x', yTitle: 'y', zTitle: 'z', axesPadding: 0, axesColor: [0, 0, 0, 255], coordinateSystem: COORDINATE_SYSTEM.CARTESIAN }; /* * @classdesc * A layer that plots a surface based on a z=f(x,y) equation. * * @class * @param {Object} [props] * @param {Function} [props.getPosition] - method called to get [x, y, z] from (u,v) values * @param {Function} [props.getColor] - method called to get color from (x,y,z) returns [r,g,b,a]. * @param {Integer} [props.uCount] - number of samples within x range * @param {Integer} [props.vCount] - number of samples within y range * @param {Number} [props.lightStrength] - front light strength * @param {Boolean} [props.drawAxes] - whether to draw axes * @param {Function} [props.getXScale] - returns a d3 scale from (params = {min, max}) * @param {Function} [props.getYScale] - returns a d3 scale from (params = {min, max}) * @param {Function} [props.getZScale] - returns a d3 scale from (params = {min, max}) * @param {Number | [Number]} [props.xTicks] - either tick counts or an array of tick values * @param {Number | [Number]} [props.yTicks] - either tick counts or an array of tick values * @param {Number | [Number]} [props.zTicks] - either tick counts or an array of tick values * @param {Function} [props.xTickFormat] - returns a string from value * @param {Function} [props.yTickFormat] - returns a string from value * @param {Function} [props.zTickFormat] - returns a string from value * @param {String} [props.xTitle] - x axis title * @param {String} [props.yTitle] - y axis title * @param {String} [props.zTitle] - z axis title * @param {Number} [props.axesPadding] - amount to set back grids from the plot, relative to the size of the bounding box * @param {Number} [props.fontSize] - size of the labels * @param {Array} [props.axesColor] - color of the gridlines, in [r,g,b,a] */ export default class PlotLayer extends CompositeLayer { updateState() { const {uCount, vCount, getPosition, getXScale, getYScale, getZScale} = this.props; // calculate z range let xMin = Infinity; let xMax = -Infinity; let yMin = Infinity; let yMax = -Infinity; let zMin = Infinity; let zMax = -Infinity; for (let vIndex = 0; vIndex < vCount; vIndex++) { for (let uIndex = 0; uIndex < uCount; uIndex++) { const u = uIndex / (uCount - 1); const v = vIndex / (vCount - 1); const [x, y, z] = getPosition(u, v); if (isFinite(x)) { xMin = Math.min(xMin, x); xMax = Math.max(xMax, x); } if (isFinite(y)) { yMin = Math.min(yMin, y); yMax = Math.max(yMax, y); } if (isFinite(z)) { zMin = Math.min(zMin, z); zMax = Math.max(zMax, z); } } } const xScale = getXScale({min: xMin, max: xMax}); const yScale = getYScale({min: yMin, max: yMax}); const zScale = getZScale({min: zMin, max: zMax}); this.setState({xScale, yScale, zScale}); } renderLayers() { const {xScale, yScale, zScale} = this.state; const { getPosition, getColor, uCount, vCount, lightStrength, fontSize, xTicks, yTicks, zTicks, xTickFormat, yTickFormat, zTickFormat, xTitle, yTitle, zTitle, axesPadding, axesColor, drawAxes, updateTriggers } = this.props; return [ new SurfaceLayer( { getPosition, getColor, uCount, vCount, xScale, yScale, zScale, lightStrength }, this.getSubLayerProps({ id: 'surface', updateTriggers }) ), new AxesLayer( { xScale, yScale, zScale, fontSize, xTicks, yTicks, zTicks, xTickFormat, yTickFormat, zTickFormat, xTitle, yTitle, zTitle, padding: axesPadding, color: axesColor }, this.getSubLayerProps({ id: 'axes' }), { visible: drawAxes, pickable: false } ) ]; } } PlotLayer.layerName = 'PlotLayer'; PlotLayer.defaultProps = defaultProps;
0
rapidsai_public_repos/node/modules/demo/deck/plot
rapidsai_public_repos/node/modules/demo/deck/plot/plot-layer/label-vertex.glsl.js
// Copyright (c) 2015 - 2017 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. export default `\ #define SHADER_NAME graph-layer-axis-vertex-shader attribute vec3 positions; attribute vec3 normals; attribute vec2 texCoords; attribute vec2 instancePositions; attribute vec3 instanceNormals; attribute float instanceIsTitle; uniform vec3 gridDims; uniform vec3 gridCenter; uniform float gridOffset; uniform vec3 labelWidths; uniform float fontSize; uniform float labelHeight; uniform vec2 labelTextureDim; varying vec2 vTexCoords; varying float shouldDiscard; const float LABEL_OFFSET = 0.02; const float TITLE_OFFSET = 0.06; float sum2(vec2 v) { return v.x + v.y; } float sum3(vec3 v) { return v.x + v.y + v.z; } // determines if the grid line is behind or in front of the center float frontFacing(vec3 v) { vec4 v_clipspace = project_uViewProjectionMatrix * project_uModelMatrix * vec4(v, 0.0); return step(v_clipspace.z, 0.0); } void main(void) { // rotated rectangle to align with slice: // for each x tick, draw rectangle on yz plane // for each y tick, draw rectangle on zx plane // for each z tick, draw rectangle on xy plane // offset of each corner of the rectangle from tick on axis vec3 gridVertexOffset = mat3( vec3(positions.z, positions.xy), vec3(positions.yz, positions.x), positions ) * instanceNormals; // normal of each edge of the rectangle from tick on axis vec3 gridLineNormal = mat3( vec3(normals.z, normals.xy), vec3(normals.yz, normals.x), normals ) * instanceNormals; // do not draw grid line in front of the graph // do not draw label behind the graph shouldDiscard = frontFacing(gridLineNormal) + (1.0 - frontFacing(gridVertexOffset)); // get bounding box of texture in pixels // +----------+----------+----------+ // | xlabel0 | ylabel0 | zlabel0 | // +----------+----------+----------+ // | xlabel1 | ylabel1 | zlabel1 | // +----------+----------+----------+ // | ... | ... | ... | vec2 textureOrigin = vec2( sum3(vec3(0.0, labelWidths.x, sum2(labelWidths.xy)) * instanceNormals), instancePositions.y * labelHeight ); vec2 textureSize = vec2(sum3(labelWidths * instanceNormals), labelHeight); vTexCoords = (textureOrigin + textureSize * texCoords) / labelTextureDim; vec3 position_modelspace = vec3(instancePositions.x) * instanceNormals + gridVertexOffset * gridDims / 2.0 + gridCenter * abs(gridVertexOffset); // apply offsets position_modelspace += gridOffset * gridLineNormal; position_modelspace += (LABEL_OFFSET + (instanceIsTitle * TITLE_OFFSET)) * gridVertexOffset; vec3 position_commonspace = project_position(position_modelspace); vec4 position_clipspace = project_common_position_to_clipspace(vec4(position_commonspace, 1.0)); vec2 labelVertexOffset = vec2(texCoords.x - 0.5, 0.5 - texCoords.y) * textureSize; // project to clipspace labelVertexOffset = project_pixel_size_to_clipspace(labelVertexOffset).xy; // scale label to be constant size in pixels labelVertexOffset *= fontSize / labelHeight * position_clipspace.w; gl_Position = position_clipspace + vec4(labelVertexOffset, 0.0, 0.0); } `;
0
rapidsai_public_repos/node/modules/demo/deck/plot
rapidsai_public_repos/node/modules/demo/deck/plot/plot-layer/fragment.glsl.js
// Copyright (c) 2015 - 2017 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. export default `\ #define SHADER_NAME graph-layer-fragment-shader precision highp float; varying vec4 vColor; varying float shouldDiscard; void main(void) { if (shouldDiscard > 0.0) { discard; } gl_FragColor = vColor; gl_FragColor = picking_filterPickingColor(gl_FragColor); } `;
0
rapidsai_public_repos/node/modules/demo/deck/plot
rapidsai_public_repos/node/modules/demo/deck/plot/plot-layer/surface-layer.js
import {Layer, picking} from '@deck.gl/core'; import GL from '@luma.gl/constants'; import {Model} from '@luma.gl/core'; import surfaceVertex from './surface-vertex.glsl'; import fragmentShader from './fragment.glsl'; const DEFAULT_COLOR = [0, 0, 0, 255]; const defaultProps = { data: [], getPosition: () => [0, 0, 0], getColor: () => DEFAULT_COLOR, xScale: null, yScale: null, zScale: null, uCount: 100, vCount: 100, lightStrength: 0.1 }; /* * @classdesc * A layer that plots a surface based on a z=f(x,y) equation. * * @class * @param {Object} [props] * @param {Function} [props.getPosition] - method called to get [x, y, z] from (u,v) values * @param {Function} [props.getColor] - method called to get color from (x,y,z) returns [r,g,b,a]. * @param {d3.scale} [props.xScale] - a d3 scale for the x axis * @param {d3.scale} [props.yScale] - a d3 scale for the y axis * @param {d3.scale} [props.zScale] - a d3 scale for the z axis * @param {Integer} [props.uCount] - number of samples within x range * @param {Integer} [props.vCount] - number of samples within y range * @param {Number} [props.lightStrength] - front light strength */ export default class SurfaceLayer extends Layer { initializeState() { const {gl} = this.context; const attributeManager = this.getAttributeManager(); const noAlloc = true; /* eslint-disable max-len */ attributeManager.add({ indices: {size: 1, isIndexed: true, update: this.calculateIndices, noAlloc}, positions: {size: 4, accessor: 'getPosition', update: this.calculatePositions, noAlloc}, colors: { size: 4, accessor: ['getPosition', 'getColor'], type: GL.UNSIGNED_BYTE, update: this.calculateColors, noAlloc }, pickingColors: {size: 3, type: GL.UNSIGNED_BYTE, update: this.calculatePickingColors, noAlloc} }); /* eslint-enable max-len */ gl.getExtension('OES_element_index_uint'); this.setState({ model: this.getModel(gl) }); } updateState({oldProps, props, changeFlags}) { if (changeFlags.propsChanged) { const {uCount, vCount} = props; if (oldProps.uCount !== uCount || oldProps.vCount !== vCount) { this.setState({ vertexCount: uCount * vCount }); this.getAttributeManager().invalidateAll(); } } } getModel(gl) { // 3d surface return new Model(gl, { id: `${this.props.id}-surface`, vs: surfaceVertex, fs: fragmentShader, modules: [picking], drawMode: GL.TRIANGLES, vertexCount: 0, isIndexed: true }); } draw({uniforms}) { const {lightStrength} = this.props; this.state.model .setUniforms( Object.assign({}, uniforms, { lightStrength }) ) .draw(); } /* * y 1 * ^ * | * | * | * 0--------> 1 * x */ encodePickingColor(i) { const {uCount, vCount} = this.props; const xIndex = i % uCount; const yIndex = (i - xIndex) / uCount; return [(xIndex / (uCount - 1)) * 255, (yIndex / (vCount - 1)) * 255, 1]; } decodePickingColor([r, g, b]) { if (b === 0) { return -1; } return [r / 255, g / 255]; } getPickingInfo(opts) { const {info} = opts; if (info && info.index !== -1) { const [u, v] = info.index; const {getPosition} = this.props; info.sample = getPosition(u, v); } return info; } calculateIndices(attribute) { const {uCount, vCount} = this.props; // # of squares = (nx - 1) * (ny - 1) // # of triangles = squares * 2 // # of indices = triangles * 3 const indicesCount = (uCount - 1) * (vCount - 1) * 2 * 3; const indices = new Uint32Array(indicesCount); let i = 0; for (let xIndex = 0; xIndex < uCount - 1; xIndex++) { for (let yIndex = 0; yIndex < vCount - 1; yIndex++) { /* * i0 i1 * +--.+--- * | / | * +'--+--- * | | * i2 i3 */ const i0 = yIndex * uCount + xIndex; const i1 = i0 + 1; const i2 = i0 + uCount; const i3 = i2 + 1; indices[i++] = i0; indices[i++] = i2; indices[i++] = i1; indices[i++] = i1; indices[i++] = i2; indices[i++] = i3; } } attribute.value = indices; this.state.model.setVertexCount(indicesCount); } // the fourth component is a flag for invalid z (NaN or Infinity) /* eslint-disable max-statements */ calculatePositions(attribute) { const {vertexCount} = this.state; const {uCount, vCount, getPosition, xScale, yScale, zScale} = this.props; const value = new Float32Array(vertexCount * attribute.size); let i = 0; for (let vIndex = 0; vIndex < vCount; vIndex++) { for (let uIndex = 0; uIndex < uCount; uIndex++) { const u = uIndex / (uCount - 1); const v = vIndex / (vCount - 1); const [x, y, z] = getPosition(u, v); const isXFinite = isFinite(x); const isYFinite = isFinite(y); const isZFinite = isFinite(z); // swap z and y: y is up in the default viewport value[i++] = isXFinite ? xScale(x) : xScale.range()[0]; value[i++] = isZFinite ? zScale(z) : zScale.range()[0]; value[i++] = isYFinite ? yScale(y) : yScale.range()[0]; value[i++] = isXFinite && isYFinite && isZFinite ? 0 : 1; } } attribute.value = value; } /* eslint-enable max-statements */ calculateColors(attribute) { const {vertexCount} = this.state; const attributeManager = this.getAttributeManager(); // reuse the calculated [x, y, z] in positions const positions = attributeManager.attributes.positions.value; const value = new Uint8ClampedArray(vertexCount * attribute.size); // Support constant colors let {getColor} = this.props; getColor = typeof getColor === 'function' ? getColor : () => getColor; for (let i = 0; i < vertexCount; i++) { const index = i * 4; const color = getColor(positions[index], positions[index + 2], positions[index + 1]); value[i * 4] = color[0]; value[i * 4 + 1] = color[1]; value[i * 4 + 2] = color[2]; value[i * 4 + 3] = isNaN(color[3]) ? 255 : color[3]; } attribute.value = value; } calculatePickingColors(attribute) { const {vertexCount} = this.state; const value = new Uint8ClampedArray(vertexCount * attribute.size); for (let i = 0; i < vertexCount; i++) { const pickingColor = this.encodePickingColor(i); value[i * 3] = pickingColor[0]; value[i * 3 + 1] = pickingColor[1]; value[i * 3 + 2] = pickingColor[2]; } attribute.value = value; } } SurfaceLayer.layerName = 'SurfaceLayer'; SurfaceLayer.defaultProps = defaultProps;
0
rapidsai_public_repos/node/modules/demo/deck/plot
rapidsai_public_repos/node/modules/demo/deck/plot/plot-layer/surface-vertex.glsl.js
// Copyright (c) 2015 - 2017 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. export default `\ #define SHADER_NAME graph-layer-vertex-shader attribute vec4 positions; attribute vec4 colors; attribute vec3 pickingColors; uniform float lightStrength; uniform float opacity; varying vec4 vColor; varying float shouldDiscard; void main(void) { // fit into a unit cube that centers at [0, 0, 0] vec3 position_commonspace = project_position(positions.xyz); gl_Position = project_common_position_to_clipspace(vec4(position_commonspace, 1.0)); // cheap way to produce believable front-lit effect. // Note: clipsspace depth is nonlinear and deltaZ depends on the near and far values // when creating the perspective projection matrix. vec4 position_vector = project_common_position_to_clipspace(vec4(position_commonspace, 0.0)); float fadeFactor = 1.0 - position_vector.z * lightStrength; vColor = vec4(colors.rgb * fadeFactor, colors.a * opacity) / 255.0;; picking_setPickingColor(pickingColors); shouldDiscard = positions.w; } `;
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/brushing/package.json
{ "private": true, "name": "@rapidsai/demo-deck-brushing", "version": "22.12.2", "license": "Apache-2.0", "author": "NVIDIA, Inc. (https://nvidia.com/)", "maintainers": [ "Paul Taylor <paul.e.taylor@me.com>" ], "bin": "index.js", "scripts": { "start": "node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js", "watch": "find -type f | entr -c -d -r node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js" }, "dependencies": { "@deck.gl/core": "8.8.10", "@deck.gl/extensions": "8.8.10", "@deck.gl/react": "8.8.10", "@rapidsai/jsdom": "~22.12.2", "d3-scale": "2.2.2", "gl-matrix": "3.4.3", "mjolnir.js": "2.7.1", "react": "17.0.2", "react-dom": "17.0.2", "react-map-gl": "7.0.19" }, "files": [ "app.jsx", "index.js", "package.json" ] }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/brushing/index.js
#!/usr/bin/env node // Copyright (c) 2020, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. module.exports = (glfwOptions = { title: 'Brushing Demo', transparent: false }) => { return require('@rapidsai/jsdom').RapidsJSDOM.fromReactComponent('./app.jsx', { glfwOptions, // Change cwd to the example dir so relative file paths are resolved module: {path: __dirname}, }); }; if (require.main === module) { module.exports().window.addEventListener('close', () => process.exit(0), {once: true}); }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/brushing/README.md
This is a minimal standalone version of the BrushingLayer example on [deck.gl](http://deck.gl) website. ### Usage Copy the content of this folder to your project. To see the base map, you need a [Mapbox access token](https://docs.mapbox.com/help/how-mapbox-works/access-tokens/). You can either set an environment variable: ```bash export MapboxAccessToken=<mapbox_access_token> ``` Or set `MAPBOX_TOKEN` directly in `app.js`. Other options can be found at [using with Mapbox GL](../../../docs/get-started/using-with-mapbox-gl.md). ```bash # install dependencies npm install # or yarn # bundle and serve the app with webpack npm start ``` ### Data format Sample data is stored in [deck.gl Example Data](https://github.com/uber-common/deck.gl-data/tree/master/examples/arc). To use your own data, checkout the [documentation of ArcLayer](../../../docs/layers/arc-layer.md).
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/brushing/app.jsx
/* global fetch */ import { BrushingExtension } from '@deck.gl/extensions'; import { ArcLayer, ScatterplotLayer } from '@deck.gl/layers'; import DeckGL from '@deck.gl/react'; import { scaleLinear } from 'd3-scale'; import * as React from 'react'; import { Component } from 'react'; import { StaticMap } from 'react-map-gl'; // Set your mapbox token here // const MAPBOX_TOKEN = process.env.MapboxAccessToken; // eslint-disable-line const MAPBOX_TOKEN = 'pk.eyJ1IjoicGF1bGV0YXlsb3IiLCJhIjoiY2pocHhhajlwMmtvbTMxczg0d2wzcnlwYiJ9.K0XJGZ_I7dQVIaJ8HpthTg' const TOOLTIP_STYLE = { position: 'absolute', padding: '4px', background: 'rgba(0, 0, 0, 0.8)', color: '#fff', maxWidth: '300px', fontSize: '10px', zIndex: 9, pointerEvents: 'none' }; // Source data GeoJSON const DATA_URL = 'https://raw.githubusercontent.com/uber-common/deck.gl-data/master/examples/arc/counties.json'; // eslint-disable-line export const inFlowColors = [[35, 181, 184]]; export const outFlowColors = [[166, 3, 3]]; // migrate out const SOURCE_COLOR = [166, 3, 3]; // migrate in const TARGET_COLOR = [35, 181, 184]; const INITIAL_VIEW_STATE = { longitude: -100, latitude: 40.7, zoom: 3, maxZoom: 15, pitch: 0, bearing: 0 }; const brushingExtension = new BrushingExtension(); /* eslint-disable react/no-deprecated */ export default class App extends Component { constructor(props) { super(props); this.state = { arcs: [], targets: [], sources: [], ...this._getLayerData(props) }; this._onHover = this._onHover.bind(this); fetch(DATA_URL) .then(response => response.json()) .then(({ features }) => { this.setState(this._getLayerData({ data: features })); }); } _onHover({ x, y, object }) { this.setState({ x, y, hoveredObject: object }); } _getLayerData({ data }) { if (!data || !data.length) { return null; } const arcs = []; const targets = []; const sources = []; const pairs = {}; data.forEach((county, i) => { const { flows, centroid: targetCentroid } = county.properties; const value = { gain: 0, loss: 0 }; Object.keys(flows).forEach(toId => { value[flows[toId] > 0 ? 'gain' : 'loss'] += flows[toId]; // if number too small, ignore it if (Math.abs(flows[toId]) < 50) { return; } const pairKey = [i, Number(toId)].sort((a, b) => a - b).join('-'); const sourceCentroid = data[toId].properties.centroid; const gain = Math.sign(flows[toId]); // add point at arc source sources.push({ position: sourceCentroid, target: targetCentroid, name: data[toId].properties.name, radius: 3, gain: -gain }); // eliminate duplicates arcs if (pairs[pairKey]) { return; } pairs[pairKey] = true; arcs.push({ target: gain > 0 ? targetCentroid : sourceCentroid, source: gain > 0 ? sourceCentroid : targetCentroid, value: flows[toId] }); }); // add point at arc target targets.push({ ...value, position: [targetCentroid[0], targetCentroid[1], 10], net: value.gain + value.loss, name: county.properties.name }); }); // sort targets by radius large -> small targets.sort((a, b) => Math.abs(b.net) - Math.abs(a.net)); const sizeScale = scaleLinear().domain([0, Math.abs(targets[0].net)]).range([36, 400]); targets.forEach(pt => { pt.radius = Math.sqrt(sizeScale(Math.abs(pt.net))); }); return { arcs, targets, sources }; } _renderTooltip() { const { x, y, hoveredObject } = this.state; if (!hoveredObject) { return null; } return ( <div style={{ ...TOOLTIP_STYLE, left: x, top: y }}> <div>{hoveredObject.name}</div> <div>{`Net gain: ${hoveredObject.net}`}</div> </div> ); } _renderLayers() { const { enableBrushing = true, brushRadius = 100000, strokeWidth = 2, opacity = 0.7 } = this.props; const { arcs, targets, sources } = this.state; if (!arcs || !targets) { return null; } return [ new ScatterplotLayer({ id: 'sources', data: sources, brushingRadius: brushRadius, brushingEnabled: enableBrushing, pickable: false, // only show source points when brushing radiusScale: enableBrushing ? 3000 : 0, getFillColor: d => (d.gain > 0 ? TARGET_COLOR : SOURCE_COLOR), extensions: [brushingExtension] }), new ScatterplotLayer({ id: 'targets-ring', data: targets, brushingRadius: brushRadius, lineWidthMinPixels: 2, stroked: true, filled: false, brushingEnabled: enableBrushing, // only show rings when brushing radiusScale: enableBrushing ? 4000 : 0, getLineColor: d => (d.net > 0 ? TARGET_COLOR : SOURCE_COLOR), extensions: [brushingExtension] }), new ScatterplotLayer({ id: 'targets', data: targets, brushingRadius: brushRadius, brushingEnabled: enableBrushing, pickable: true, radiusScale: 3000, onHover: this._onHover, getFillColor: d => (d.net > 0 ? TARGET_COLOR : SOURCE_COLOR), extensions: [brushingExtension] }), new ArcLayer({ id: 'arc', data: arcs, getWidth: strokeWidth, opacity, brushingRadius: brushRadius, brushingEnabled: enableBrushing, getSourcePosition: d => d.source, getTargetPosition: d => d.target, getSourceColor: SOURCE_COLOR, getTargetColor: TARGET_COLOR, extensions: [brushingExtension] }) ]; } render() { const { mapStyle = 'https://basemaps.cartocdn.com/gl/dark-matter-nolabels-gl-style/style.json' } = this.props; return ( <DeckGL ref={this._deckRef} layers={this._renderLayers()} initialViewState={INITIAL_VIEW_STATE} controller={true} > <StaticMap reuseMaps mapStyle={mapStyle} preventStyleDiffing={true} mapboxApiAccessToken={MAPBOX_TOKEN} /> {this._renderTooltip()} </DeckGL> ); } }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/arc/package.json
{ "private": true, "name": "@rapidsai/demo-deck-arc", "version": "22.12.2", "license": "Apache-2.0", "author": "NVIDIA, Inc. (https://nvidia.com/)", "maintainers": [ "Paul Taylor <paul.e.taylor@me.com>" ], "bin": "index.js", "scripts": { "start": "node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js", "watch": "find -type f | entr -c -d -r node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js" }, "dependencies": { "@deck.gl/core": "8.8.10", "@deck.gl/layers": "8.8.10", "@deck.gl/mapbox": "8.8.10", "@rapidsai/jsdom": "~22.12.2", "d3-scale": "2.2.2", "maplibre-gl": "2.4.0", "mjolnir.js": "2.7.1", "react": "17.0.2", "react-dom": "17.0.2" }, "files": [ "app.js", "index.js", "package.json" ] }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/arc/index.js
#!/usr/bin/env node // Copyright (c) 2020-2023, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. module.exports = (glfwOptions = { title: 'Arc Demo', transparent: false }) => { const jsdom = new (require('@rapidsai/jsdom').RapidsJSDOM)({ glfwOptions, // Change cwd to the example dir so relative file paths are resolved module: {path: __dirname}, }); return Object.assign(jsdom, { loaded: jsdom.loaded.then(() => jsdom.window.evalFn(async () => await import('./app.js'))), }); }; if (require.main === module) { module.exports().window.addEventListener('close', () => process.exit(0), {once: true}); }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/arc/README.md
This is a minimal standalone version of the ArcLayer example on [deck.gl](http://deck.gl) website. ### Usage Copy the content of this folder to your project. To see the base map, you need a [Mapbox access token](https://docs.mapbox.com/help/how-mapbox-works/access-tokens/). You can either set an environment variable: ```bash export MapboxAccessToken=<mapbox_access_token> ``` Or set `MAPBOX_TOKEN` directly in `app.js`. Other options can be found at [using with Mapbox GL](../../../docs/get-started/using-with-mapbox-gl.md). ```bash # install dependencies npm install # or yarn # bundle and serve the app with webpack npm start ``` ### Data format Sample data is stored in [deck.gl Example Data](https://github.com/uber-common/deck.gl-data/tree/master/examples/arc). To use your own data, checkout the [documentation of ArcLayer](../../../docs/layers/arc-layer.md).
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/arc/app.js
// Copyright (c) 2022, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import {log as deckLog} from '@deck.gl/core'; import {ArcLayer, GeoJsonLayer} from '@deck.gl/layers'; import {MapboxOverlay} from '@deck.gl/mapbox'; import {scaleQuantile} from 'd3-scale'; import * as maplibre from 'maplibre-gl'; deckLog.level = 0; deckLog.enable(false); const mapStyle = 'https://basemaps.cartocdn.com/gl/dark-matter-nolabels-gl-style/style.json'; const DATA_URL = 'https://raw.githubusercontent.com/uber-common/deck.gl-data/master/examples/arc/counties.json'; const INITIAL_VIEW_STATE = { longitude: -100, latitude: 40.7, zoom: 3, maxZoom: 15, pitch: 30, bearing: 30, }; // Add MapLibre GL for the basemap const map = new maplibre.Map({ style: mapStyle, interactive: true, container: document.body, zoom: INITIAL_VIEW_STATE.zoom, pitch: INITIAL_VIEW_STATE.pitch, bearing: INITIAL_VIEW_STATE.bearing, maxZoom: INITIAL_VIEW_STATE.maxZoom, center: [ INITIAL_VIEW_STATE.longitude, INITIAL_VIEW_STATE.latitude, ], }); map.scrollZoom.setWheelZoomRate(1 / 25); const deck = new MapboxOverlay({layers: [], interleaved: true}); map.addControl(deck); fetch(DATA_URL) .then(response => response.json()) .then(({features}) => getLayers(calcArcs(features))) // .then((props) => deck.setProps(props)); function calcArcs(data, selectedCounty = deck._props.selectedCounty) { if (!data || !data.length) { return; } if (!selectedCounty) { // selectedCounty = data.find(f => f.properties.name === 'Los Angeles, CA'); } const {flows, centroid} = selectedCounty.properties; const arcs = Object.keys(flows).map(toId => { const f = data[toId]; return { source: centroid, target: f.properties.centroid, value: flows[toId], }; }); const scale = scaleQuantile().domain(arcs.map(a => Math.abs(a.value))).range(inFlowColors.map((c, i) => i)); arcs.forEach(a => { a.gain = Math.sign(a.value); a.quantile = scale(Math.abs(a.value)); }); return {data, arcs, selectedCounty}; } function getLayers({data, arcs, ...props}) { return { ...props, layers: [ new GeoJsonLayer({ id: 'geojson', data: data, filled: true, stroked: true, pickable: true, autoHighlight: true, lineWidthMinPixels: 1, getLineWidth: 1, getFillColor: [0, 0, 0, 0], getLineColor: [255, 255, 255, 135], onHover: ({x, y, object}) => deck.setProps({x, y, hoveredCounty: object}), onClick: ({object}) => deck.setProps(getLayers(calcArcs(data, object))), }), new ArcLayer({ id: 'arc', data: arcs, getWidth: 2, getSourcePosition: d => d.source, getTargetPosition: d => d.target, getSourceColor: d => (d.gain > 0 ? inFlowColors : outFlowColors)[d.quantile], getTargetColor: d => (d.gain > 0 ? outFlowColors : inFlowColors)[d.quantile], }), ] }; } const inFlowColors = [ [255, 255, 204], [199, 233, 180], [127, 205, 187], [65, 182, 196], [29, 145, 192], [34, 94, 168], [12, 44, 132] ]; const outFlowColors = [ [255, 255, 178], [254, 217, 118], [254, 178, 76], [253, 141, 60], [252, 78, 42], [227, 26, 28], [177, 0, 38] ];
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/scenegraph-layer/package.json
{ "private": true, "name": "@rapidsai/demo-deck-scenegraph-layer-demo", "version": "22.12.2", "license": "Apache-2.0", "author": "NVIDIA, Inc. (https://nvidia.com/)", "maintainers": [ "Paul Taylor <paul.e.taylor@me.com>" ], "bin": "index.js", "scripts": { "start": "node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js", "watch": "find -type f | entr -c -d -r node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js" }, "dependencies": { "@deck.gl/mesh-layers": "8.8.10", "@deck.gl/react": "8.8.10", "@loaders.gl/core": "3.2.9", "@loaders.gl/gltf": "3.2.9", "@rapidsai/jsdom": "~22.12.2", "react": "17.0.2", "react-dom": "17.0.2", "react-map-gl": "7.0.19" }, "files": [ "app.jsx", "index.js", "package.json" ] }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/scenegraph-layer/index.js
#!/usr/bin/env node // Copyright (c) 2020, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. module.exports = (glfwOptions = { title: 'SceneGraph Layer Demo', transparent: false }) => { return require('@rapidsai/jsdom').RapidsJSDOM.fromReactComponent('./app.jsx', { glfwOptions, // Change cwd to the example dir so relative file paths are resolved module: {path: __dirname}, }); }; if (require.main === module) { module.exports().window.addEventListener('close', () => process.exit(0), {once: true}); }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/scenegraph-layer/README.md
This is a standalone demo of the [scenegraph layer](./scenegraph-layer) built upon [deck.gl](http://deck.gl). This example illustrates the scenegraph layer features. ### Usage Copy the content of this folder to your project. To see the base map, you need a [Mapbox access token](https://docs.mapbox.com/help/how-mapbox-works/access-tokens/). You can either set an environment variable: ```bash export MapboxAccessToken=<mapbox_access_token> ``` Or set `MAPBOX_TOKEN` directly in `app.js`. Other options can be found at [using with Mapbox GL](../../../docs/get-started/using-with-mapbox-gl.md). ```bash # install dependencies npm install # or yarn # bundle and serve the app with webpack npm start ``` ### Model Model by `manilov.ap`, modified for the application. Original: https://sketchfab.com/3d-models/boeing747-1a75633f5737462ebc1c7879869f6229 [CC Attribution](https://creativecommons.org/licenses/by/4.0/) ### Data source The data is from [Opensky Network](https://opensky-network.org).
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/scenegraph-layer/app.jsx
/* global fetch, setTimeout, clearTimeout */ import * as React from 'react' import { Component, Fragment } from 'react'; import { render } from 'react-dom'; import { StaticMap } from 'react-map-gl'; import DeckGL from '@deck.gl/react'; import { ScenegraphLayer } from '@deck.gl/mesh-layers'; import { GLTFLoader } from '@loaders.gl/gltf'; import { registerLoaders } from '@loaders.gl/core'; registerLoaders([GLTFLoader]); // Set your mapbox token here const MAPBOX_TOKEN = process.env.MapboxAccessToken; // eslint-disable-line // mapbox style file path const MAPBOX_STYLE = 'https://rivulet-zhang.github.io/dataRepo/mapbox/style/map-style-dark-v9-no-labels.json'; const DATA_URL = 'https://opensky-network.org/api/states/all'; const MODEL_URL = 'https://raw.githubusercontent.com/uber-common/deck.gl-data/master/examples/scenegraph-layer/airplane.glb'; const REFRESH_TIME = 30000; const ANIMATIONS = { '*': { speed: 1 } }; const INITIAL_VIEW_STATE = { latitude: 39.1, longitude: -94.57, zoom: 3.8, maxZoom: 16, pitch: 0, bearing: 0 }; const DATA_INDEX = { UNIQUE_ID: 0, ORIGIN_COUNTRY: 2, LONGITUDE: 5, LATITUDE: 6, BARO_ALTITUDE: 7, VELOCITY: 9, TRUE_TRACK: 10, VERTICAL_RATE: 11, GEO_ALTITUDE: 13, POSITION_SOURCE: 16 }; export default class App extends Component { constructor(props) { super(props); this.state = {}; this._loadData(); } componentWillUnmount() { this.unmounted = true; if (this.state.nextTimeoutId) { clearTimeout(this.state.nextTimeoutId); } } _sort(data, oldData) { // In order to keep the animation smooth we need to always return the same // objects in the exact same order. This function will discard new objects // and only update existing ones. if (!oldData) { return data; } const dataAsObj = {}; data.forEach(entry => (dataAsObj[entry[DATA_INDEX.UNIQUE_ID]] = entry)); return oldData.map(entry => dataAsObj[entry[DATA_INDEX.UNIQUE_ID]] || entry); } _loadData() { fetch(DATA_URL) .then(resp => resp.json()) .then(resp => { if (resp && resp.states && !this.unmounted) { const nextTimeoutId = setTimeout(() => this._loadData(), REFRESH_TIME); this.setState({ data: this._sort(resp.states, this.state.data), nextTimeoutId }); } }); } _verticalRateToAngle(object) { // Return: -90 looking up, +90 looking down const verticalRate = object[DATA_INDEX.VERTICAL_RATE] || 0; const velocity = object[DATA_INDEX.VELOCITY] || 0; return (-Math.atan2(verticalRate, velocity) * 180) / Math.PI; } _renderLayers() { const { data } = this.state; if (Array.isArray(data)) { return [ new ScenegraphLayer({ id: 'scenegraph-layer', data, pickable: true, sizeScale: 250, scenegraph: MODEL_URL, _animations: ANIMATIONS, sizeMinPixels: 0.1, sizeMaxPixels: 1.5, getPosition: d => [ d[DATA_INDEX.LONGITUDE] || 0, d[DATA_INDEX.LATITUDE] || 0, d[DATA_INDEX.GEO_ALTITUDE] || 0 ], getOrientation: d => [this._verticalRateToAngle(d), -d[DATA_INDEX.TRUE_TRACK] || 0, 90], getTranslation: [0, 0, 0], getScale: [1, 1, 1], transitions: { getPosition: REFRESH_TIME * 0.9 }, onHover: ({ object }) => this.setState({ hoverObject: object }) }) ]; } return []; } _renderHoverObject() { const [icao24 = '', callsign = '', originCountry = ''] = this.state.hoverObject; const verticalRate = this.state.hoverObject[DATA_INDEX.VERTICAL_RATE] || 0; const velocity = this.state.hoverObject[DATA_INDEX.VELOCITY] || 0; const track = this.state.hoverObject[DATA_INDEX.TRUE_TRACK] || 0; return ( <Fragment> <div>&nbsp;</div> <div>Unique ID: {icao24}</div> <div>Call Sign: {callsign}</div> <div>Country: {originCountry}</div> <div>Vertical Rate: {verticalRate} m/s</div> <div>Velocity: {velocity} m/s</div> <div>Direction: {track}</div> </Fragment> ); } _renderInfoBox() { return ( <div style={{ position: 'fixed', right: 8, top: 8, width: 140, background: 'rgba(0,0,255,0.3)', borderRadius: 8, color: 'white', padding: 8, fontSize: 12 }} > Data provided by{' '} <a style={{ color: 'white' }} href="http://www.opensky-network.org" target="_blank" rel="noopener noreferrer" > The OpenSky Network, http://www.opensky-network.org </a> {this.state.hoverObject && this._renderHoverObject()} </div> ); } render() { const { mapStyle = MAPBOX_STYLE } = this.props; return ( <Fragment> <DeckGL layers={this._renderLayers()} initialViewState={INITIAL_VIEW_STATE} controller={true} _animate > <StaticMap reuseMaps mapStyle={mapStyle} preventStyleDiffing={true} mapboxApiAccessToken={MAPBOX_TOKEN} /> </DeckGL> {this._renderInfoBox()} </Fragment> ); } } export function renderToDOM(container) { render(<App />, container); }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/line/package.json
{ "private": true, "name": "@rapidsai/demo-deck-line", "version": "22.12.2", "license": "Apache-2.0", "author": "NVIDIA, Inc. (https://nvidia.com/)", "maintainers": [ "Paul Taylor <paul.e.taylor@me.com>" ], "bin": "index.js", "scripts": { "start": "node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js", "watch": "find -type f | entr -c -d -r node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js" }, "dependencies": { "@deck.gl/core": "8.8.10", "@deck.gl/layers": "8.8.10", "@deck.gl/react": "8.8.10", "@luma.gl/constants": "8.5.16", "@rapidsai/jsdom": "~22.12.2", "mjolnir.js": "2.7.1", "react": "17.0.2", "react-dom": "17.0.2", "react-map-gl": "7.0.19" }, "files": [ "app.jsx", "index.js", "package.json" ] }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/line/index.js
#!/usr/bin/env node // Copyright (c) 2020, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. module.exports = (glfwOptions = { title: 'Line Demo', transparent: false }) => { return require('@rapidsai/jsdom').RapidsJSDOM.fromReactComponent('./app.jsx', { glfwOptions, // Change cwd to the example dir so relative file paths are resolved module: {path: __dirname}, }); }; if (require.main === module) { module.exports().window.addEventListener('close', () => process.exit(0), {once: true}); }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/line/README.md
This is a minimal standalone version of the LineLayer example on [deck.gl](http://deck.gl) website. ### Usage Copy the content of this folder to your project. To see the base map, you need a [Mapbox access token](https://docs.mapbox.com/help/how-mapbox-works/access-tokens/). You can either set an environment variable: ```bash export MapboxAccessToken=<mapbox_access_token> ``` Or set `MAPBOX_TOKEN` directly in `app.js`. Other options can be found at [using with Mapbox GL](../../../docs/get-started/using-with-mapbox-gl.md). ```bash # install dependencies npm install # or yarn # bundle and serve the app with webpack npm start ``` ### Data format Sample data is stored in [deck.gl Example Data](https://github.com/uber-common/deck.gl-data/tree/master/examples/line). To use your own data, checkout the [documentation of LineLayer](../../../docs/layers/line-layer.md).
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/line/app.jsx
import * as React from 'react'; import { Component } from 'react'; import { render } from 'react-dom'; import DeckGL from '@deck.gl/react'; import { LineLayer, ScatterplotLayer } from '@deck.gl/layers'; import GL from '@luma.gl/constants'; import { StaticMap } from 'react-map-gl'; import { log as deckLog } from '@deck.gl/core'; deckLog.level = 0; deckLog.enable(false); // Set your mapbox token here const MAPBOX_TOKEN = 'pk.eyJ1Ijoid21qcGlsbG93IiwiYSI6ImNrN2JldzdpbDA2Ym0zZXFzZ3oydXN2ajIifQ.qPOZDsyYgMMUhxEKrvHzRA'; // eslint-disable-line // Source data CSV const DATA_URL = { AIRPORTS: 'https://raw.githubusercontent.com/uber-common/deck.gl-data/master/examples/line/airports.json', // eslint-disable-line FLIGHT_PATHS: 'https://raw.githubusercontent.com/uber-common/deck.gl-data/master/examples/line/heathrow-flights.json' // eslint-disable-line }; const INITIAL_VIEW_STATE = { latitude: 47.65, longitude: 7, zoom: 4.5, maxZoom: 16, pitch: 50, bearing: 0 }; function getColor(d) { const z = d.start[2]; const r = z / 10000; return [255 * (1 - r * 2), 128 * r, 255 * r, 255 * (1 - r)]; } function getSize(type) { if (type.search('major') >= 0) { return 100; } if (type.search('small') >= 0) { return 30; } return 60; } export default class App extends Component { constructor(props) { super(props); this.state = { hoveredObject: null }; this._onHover = this._onHover.bind(this); this._renderTooltip = this._renderTooltip.bind(this); } _onHover({ x, y, object }) { this.setState({ x, y, hoveredObject: object }); } _renderTooltip() { const { x, y, hoveredObject } = this.state; return ( hoveredObject && ( <div className="tooltip" style={{ left: x, top: y }}> <div>{hoveredObject.country || hoveredObject.abbrev}</div> <div>{hoveredObject.name.indexOf('0x') >= 0 ? '' : hoveredObject.name}</div> </div> ) ); } _renderLayers() { const { airports = DATA_URL.AIRPORTS, flightPaths = DATA_URL.FLIGHT_PATHS, getWidth = 3 } = this.props; return [ new ScatterplotLayer({ id: 'airports', data: airports, radiusScale: 20, getPosition: d => d.coordinates, getFillColor: [255, 140, 0], getRadius: d => getSize(d.type), pickable: true, onHover: this._onHover }), new LineLayer({ id: 'flight-paths', data: flightPaths, opacity: 0.8, getSourcePosition: d => d.start, getTargetPosition: d => d.end, getColor, getWidth, pickable: true, onHover: this._onHover }) ]; } render() { const { mapStyle = 'https://basemaps.cartocdn.com/gl/dark-matter-nolabels-gl-style/style.json' } = this.props; return ( <DeckGL layers={this._renderLayers()} initialViewState={INITIAL_VIEW_STATE} controller={true} pickingRadius={5} parameters={{ blendFunc: [GL.SRC_ALPHA, GL.ONE, GL.ONE_MINUS_DST_ALPHA, GL.ONE], blendEquation: GL.FUNC_ADD }} > <StaticMap reuseMaps mapStyle={mapStyle} preventStyleDiffing={true} mapboxApiAccessToken={MAPBOX_TOKEN} /> {this._renderTooltip} </DeckGL> ); } } export function renderToDOM(container) { render(<App />, container); }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/3d-heatmap/package.json
{ "private": true, "name": "@rapidsai/demo-deck-3d-heatmap", "version": "22.12.2", "license": "Apache-2.0", "author": "NVIDIA, Inc. (https://nvidia.com/)", "maintainers": [ "Paul Taylor <paul.e.taylor@me.com>" ], "bin": "index.js", "scripts": { "start": "node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js", "watch": "find -type f | entr -c -d -r node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js" }, "dependencies": { "@deck.gl/aggregation-layers": "8.8.10", "@deck.gl/core": "8.8.10", "@deck.gl/react": "8.8.10", "@rapidsai/jsdom": "~22.12.2", "d3-request": "1.0.6", "mjolnir.js": "2.7.1", "react": "17.0.2", "react-dom": "17.0.2", "react-map-gl": "7.0.19" }, "files": [ "app.jsx", "index.js", "package.json" ] }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/3d-heatmap/index.js
#!/usr/bin/env node // Copyright (c) 2020, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. module.exports = (glfwOptions = { title: '3D Heatmap Demo', transparent: false }) => { return require('@rapidsai/jsdom').RapidsJSDOM.fromReactComponent('./app.jsx', { glfwOptions, // Change cwd to the example dir so relative file paths are resolved module: {path: __dirname}, }); }; if (require.main === module) { module.exports().window.addEventListener('close', () => process.exit(0), {once: true}); }
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/3d-heatmap/README.md
This is a minimal standalone version of the 3DHeatmap example on [deck.gl](http://deck.gl) website. ### Usage Copy the content of this folder to your project. To see the base map, you need a [Mapbox access token](https://docs.mapbox.com/help/how-mapbox-works/access-tokens/). You can either set an environment variable: ```bash export MapboxAccessToken=<mapbox_access_token> ``` Or set `MAPBOX_TOKEN` directly in `app.js`. Other options can be found at [using with Mapbox GL](../../../docs/get-started/using-with-mapbox-gl.md). ```bash # install dependencies npm install # or yarn # bundle and serve the app with webpack npm start ``` ### Data format Sample data is stored in [deck.gl Example Data](https://github.com/uber-common/deck.gl-data/tree/master/examples/3d-heatmap). To use your own data, checkout the [documentation of HexagonLayer](../../../docs/layers/hexagon-layer.md)
0
rapidsai_public_repos/node/modules/demo/deck
rapidsai_public_repos/node/modules/demo/deck/3d-heatmap/app.jsx
import { HexagonLayer } from '@deck.gl/aggregation-layers'; import { AmbientLight, LightingEffect, PointLight } from '@deck.gl/core'; import DeckGL from '@deck.gl/react'; import * as React from 'react'; import { Component } from 'react'; import { StaticMap } from 'react-map-gl'; // Set your mapbox token here const MAPBOX_TOKEN = 'pk.eyJ1Ijoid21qcGlsbG93IiwiYSI6ImNrN2JldzdpbDA2Ym0zZXFzZ3oydXN2ajIifQ.qPOZDsyYgMMUhxEKrvHzRA'; // eslint-disable-line // Source data CSV const DATA_URL = 'https://raw.githubusercontent.com/uber-common/deck.gl-data/master/examples/3d-heatmap/heatmap-data.csv'; // eslint-disable-line const ambientLight = new AmbientLight({ color: [255, 255, 255], intensity: 1.0 }); const pointLight1 = new PointLight({ color: [255, 255, 255], intensity: 0.8, position: [-0.144528, 49.739968, 80000] }); const pointLight2 = new PointLight({ color: [255, 255, 255], intensity: 0.8, position: [-3.807751, 54.104682, 8000] }); const lightingEffect = new LightingEffect({ ambientLight, pointLight1, pointLight2 }); const material = { ambient: 0.64, diffuse: 0.6, shininess: 32, specularColor: [51, 51, 51] }; const INITIAL_VIEW_STATE = { longitude: -1.4157267858730052, latitude: 52.232395363869415, zoom: 6.6, minZoom: 5, maxZoom: 15, pitch: 40.5, bearing: -27.396674584323023 }; const colorRange = [[1, 152, 189], [73, 227, 206], [216, 254, 181], [254, 237, 177], [254, 173, 84], [209, 55, 78]]; const elevationScale = { min: 1, max: 50 }; /* eslint-disable react/no-deprecated */ export default class App extends Component { static get defaultColorRange() { return colorRange; } constructor(props) { super(props); this.state = { elevationScale: elevationScale.min }; require('d3-request').csv(DATA_URL, (error, response) => { if (!error) { this.setState({ data: response.map(d => [Number(d.lng), Number(d.lat)]) }); } }); } _renderLayers() { const { data } = this.state; const { radius = 1000, upperPercentile = 100, coverage = 1 } = this.props; return [new HexagonLayer({ id: 'heatmap', colorRange, coverage, data, elevationRange: [0, 3000], elevationScale: data && data.length ? 50 : 0, extruded: true, getPosition: d => d, onHover: this.props.onHover, pickable: Boolean(this.props.onHover), radius, upperPercentile, material, transitions: { elevationScale: 3000 } })]; } render() { const { mapStyle = 'https://basemaps.cartocdn.com/gl/dark-matter-nolabels-gl-style/style.json' } = this.props; return ( <DeckGL layers={this._renderLayers()} effects={[lightingEffect]} initialViewState={INITIAL_VIEW_STATE} controller={true}> <StaticMap reuseMaps mapStyle={mapStyle} preventStyleDiffing={true} mapboxApiAccessToken={MAPBOX_TOKEN} /> </DeckGL> ); } }
0
rapidsai_public_repos/node/modules/demo/tfjs
rapidsai_public_repos/node/modules/demo/tfjs/addition-rnn/package.json
{ "private": true, "name": "@rapidsai/demo-tfjs-addition-rnn", "main": "index.js", "version": "22.12.2", "license": "Apache-2.0", "author": "NVIDIA, Inc. (https://nvidia.com/)", "maintainers": [ "Paul Taylor <paul.e.taylor@me.com>" ], "bin": "index.js", "scripts": { "start": "node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js", "watch": "find -type f | entr -c -d -r node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js" }, "dependencies": { "@rapidsai/glfw": "~22.12.2", "@tensorflow/tfjs": "2.8.6", "chalk": "^4.1.1" }, "files": [ "app.js", "demo.js", "index.js", "package.json" ] }
0
rapidsai_public_repos/node/modules/demo/tfjs
rapidsai_public_repos/node/modules/demo/tfjs/addition-rnn/index.js
#!/usr/bin/env node // Copyright (c) 2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. module.exports = () => { const {GLFWOpenGLProfile} = require('@rapidsai/glfw'); const {RapidsJSDOM} = require('@rapidsai/jsdom'); const jsdom = new RapidsJSDOM({ // Change cwd to the example dir so relative file paths are resolved module: {path: __dirname}, glfwOptions: {openGLProfile: GLFWOpenGLProfile.COMPAT} }); jsdom.window.evalFn(() => { require('./app.js'); }); return jsdom; }; if (require.main === module) { // ensure demo is run with headless EGL delete process.env.DISPLAY; module.exports().window.addEventListener('close', () => process.exit(0), {once: true}); }
0
rapidsai_public_repos/node/modules/demo/tfjs
rapidsai_public_repos/node/modules/demo/tfjs/addition-rnn/demo.js
/** * @license * Copyright 2018 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ /** * Addition RNN example. * * Based on Python Keras example: * https://github.com/keras-team/keras/blob/master/examples/addition_rnn.py */ import * as tf from '@tensorflow/tfjs'; // import * as tfvis from '@tensorflow/tfjs-vis'; class CharacterTable { /** * Constructor of CharacterTable. * @param chars A string that contains the characters that can appear * in the input. */ constructor(chars) { this.chars = chars; this.charIndices = {}; this.indicesChar = {}; this.size = this.chars.length; for (let i = 0; i < this.size; ++i) { const char = this.chars[i]; if (this.charIndices[char] != null) { throw new Error(`Duplicate character '${char}'`); } this.charIndices[this.chars[i]] = i; this.indicesChar[i] = this.chars[i]; } } /** * Convert a string into a one-hot encoded tensor. * * @param str The input string. * @param numRows Number of rows of the output tensor. * @returns The one-hot encoded 2D tensor. * @throws If `str` contains any characters outside the `CharacterTable`'s * vocabulary. */ encode(str, numRows) { const buf = tf.buffer([numRows, this.size]); for (let i = 0; i < str.length; ++i) { const char = str[i]; if (this.charIndices[char] == null) { throw new Error(`Unknown character: '${char}'`); } buf.set(1, i, this.charIndices[char]); } return buf.toTensor().as2D(numRows, this.size); } encodeBatch(strings, numRows) { const numExamples = strings.length; const buf = tf.buffer([numExamples, numRows, this.size]); for (let n = 0; n < numExamples; ++n) { const str = strings[n]; for (let i = 0; i < str.length; ++i) { const char = str[i]; if (this.charIndices[char] == null) { throw new Error(`Unknown character: '${char}'`); } buf.set(1, n, i, this.charIndices[char]); } } return buf.toTensor().as3D(numExamples, numRows, this.size); } /** * Convert a 2D tensor into a string with the CharacterTable's vocabulary. * * @param x Input 2D tensor. * @param calcArgmax Whether to perform `argMax` operation on `x` before * indexing into the `CharacterTable`'s vocabulary. * @returns The decoded string. */ decode(x, calcArgmax = true) { return tf.tidy(() => { if (calcArgmax) { x = x.argMax(1); } const xData = x.dataSync(); // TODO(cais): Performance implication? let output = ''; for (const index of Array.from(xData)) { output += this.indicesChar[index]; } return output; }); } } /** * Generate examples. * * Each example consists of a question, e.g., '123+456' and and an * answer, e.g., '579'. * * @param digits Maximum number of digits of each operand of the * @param numExamples Number of examples to generate. * @param invert Whether to invert the strings in the question. * @returns The generated examples. */ function generateData(digits, numExamples, invert) { const digitArray = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']; const arraySize = digitArray.length; const output = []; const maxLen = digits + 1 + digits; const f = () => { let str = ''; while (str.length < digits) { const index = Math.floor(Math.random() * arraySize); str += digitArray[index]; } return Number.parseInt(str); }; const seen = new Set(); while (output.length < numExamples) { const a = f(); const b = f(); const sorted = b > a ? [a, b] : [b, a]; const key = sorted[0] + '`' + sorted[1]; if (seen.has(key)) { continue; } seen.add(key); // Pad the data with spaces such that it is always maxLen. const q = `${a}+${b}`; const query = q + ' '.repeat(maxLen - q.length); let ans = (a + b).toString(); // Answer can be of maximum size `digits + 1`. ans += ' '.repeat(digits + 1 - ans.length); if (invert) { throw new Error('invert is not implemented yet'); } output.push([query, ans]); } return output; } function convertDataToTensors(data, charTable, digits) { const maxLen = digits + 1 + digits; const questions = data.map(datum => datum[0]); const answers = data.map(datum => datum[1]); return [ charTable.encodeBatch(questions, maxLen), charTable.encodeBatch(answers, digits + 1), ]; } function createAndCompileModel( layers, hiddenSize, rnnType, digits, vocabularySize) { const maxLen = digits + 1 + digits; const model = tf.sequential(); switch (rnnType) { case 'SimpleRNN': model.add(tf.layers.simpleRNN({ units: hiddenSize, recurrentInitializer: 'glorotNormal', inputShape: [maxLen, vocabularySize] })); break; case 'GRU': model.add(tf.layers.gru({ units: hiddenSize, recurrentInitializer: 'glorotNormal', inputShape: [maxLen, vocabularySize] })); break; case 'LSTM': model.add(tf.layers.lstm({ units: hiddenSize, recurrentInitializer: 'glorotNormal', inputShape: [maxLen, vocabularySize] })); break; default: throw new Error(`Unsupported RNN type: '${rnnType}'`); } model.add(tf.layers.repeatVector({ n: digits + 1 })); switch (rnnType) { case 'SimpleRNN': model.add(tf.layers.simpleRNN({ units: hiddenSize, recurrentInitializer: 'glorotNormal', returnSequences: true })); break; case 'GRU': model.add(tf.layers.gru({ units: hiddenSize, recurrentInitializer: 'glorotNormal', returnSequences: true })); break; case 'LSTM': model.add(tf.layers.lstm({ units: hiddenSize, recurrentInitializer: 'glorotNormal', returnSequences: true })); break; default: throw new Error(`Unsupported RNN type: '${rnnType}'`); } model.add(tf.layers.timeDistributed( { layer: tf.layers.dense({ units: vocabularySize }) })); model.add(tf.layers.activation({ activation: 'softmax' })); model.compile({ loss: 'categoricalCrossentropy', optimizer: 'adam', metrics: ['accuracy'] }); return model; } class AdditionRNNDemo { constructor(digits, trainingSize, rnnType, layers, hiddenSize) { // Prepare training data. const chars = '0123456789+ '; this.charTable = new CharacterTable(chars); console.log('Generating training data'); const data = generateData(digits, trainingSize, false); const split = Math.floor(trainingSize * 0.9); this.trainData = data.slice(0, split); this.testData = data.slice(split); [this.trainXs, this.trainYs] = convertDataToTensors(this.trainData, this.charTable, digits); [this.testXs, this.testYs] = convertDataToTensors(this.testData, this.charTable, digits); this.model = createAndCompileModel( layers, hiddenSize, rnnType, digits, chars.length); } async train(iterations, batchSize, numTestExamples) { const lossValues = [[], []]; const accuracyValues = [[], []]; for (let i = 0; i < iterations; ++i) { const beginMs = performance.now(); const history = await this.model.fit(this.trainXs, this.trainYs, { epochs: 1, batchSize, validationData: [this.testXs, this.testYs], yieldEvery: 'epoch' }); const elapsedMs = performance.now() - beginMs; const modelFitTime = elapsedMs / 1000; const trainLoss = history.history['loss'][0]; const trainAccuracy = history.history['acc'][0]; const valLoss = history.history['val_loss'][0]; const valAccuracy = history.history['val_acc'][0]; lossValues[0].push({ 'x': i, 'y': trainLoss }); lossValues[1].push({ 'x': i, 'y': valLoss }); accuracyValues[0].push({ 'x': i, 'y': trainAccuracy }); accuracyValues[1].push({ 'x': i, 'y': valAccuracy }); document.getElementById('trainStatus').textContent = `Iteration ${i + 1} of ${iterations}: ` + `Time per iteration: ${modelFitTime.toFixed(3)} (seconds)`; // const lossContainer = document.getElementById('lossChart'); // tfvis.render.linechart( // lossContainer, {values: lossValues, series: ['train', 'validation']}, // { // width: 420, // height: 300, // xLabel: 'epoch', // yLabel: 'loss', // }); // const accuracyContainer = document.getElementById('accuracyChart'); // tfvis.render.linechart( // accuracyContainer, // {values: accuracyValues, series: ['train', 'validation']}, { // width: 420, // height: 300, // xLabel: 'epoch', // yLabel: 'accuracy', // }); if (this.testXsForDisplay == null || this.testXsForDisplay.shape[0] !== numTestExamples) { if (this.textXsForDisplay) { this.textXsForDisplay.dispose(); } this.testXsForDisplay = this.testXs.slice( [0, 0, 0], [numTestExamples, this.testXs.shape[1], this.testXs.shape[2]]); } const examples = []; const isCorrect = []; tf.tidy(() => { const predictOut = this.model.predict(this.testXsForDisplay); for (let k = 0; k < numTestExamples; ++k) { const scores = predictOut .slice( [k, 0, 0], [1, predictOut.shape[1], predictOut.shape[2]]) .as2D(predictOut.shape[1], predictOut.shape[2]); const decoded = this.charTable.decode(scores); examples.push(this.testData[k][0] + ' = ' + decoded); isCorrect.push(this.testData[k][1].trim() === decoded.trim()); } }); const examplesDiv = document.getElementById('testExamples'); const examplesContent = examples.map( (example, i) => `<div class="${isCorrect[i] ? 'answer-correct' : 'answer-wrong'}">` + `${example}` + `</div>`); examplesDiv.innerHTML = examplesContent.join('\n'); } } } async function runAdditionRNNDemo() { document.getElementById('trainModel').addEventListener('click', async () => { const digits = +(document.getElementById('digits')).value; const trainingSize = +(document.getElementById('trainingSize')).value; const rnnTypeSelect = document.getElementById('rnnType'); const rnnType = rnnTypeSelect.options[rnnTypeSelect.selectedIndex].getAttribute( 'value'); const layers = +(document.getElementById('rnnLayers')).value; const hiddenSize = +(document.getElementById('rnnLayerSize')).value; const batchSize = +(document.getElementById('batchSize')).value; const trainIterations = +(document.getElementById('trainIterations')).value; const numTestExamples = +(document.getElementById('numTestExamples')).value; // Do some checks on the user-specified parameters. const status = document.getElementById('trainStatus'); if (digits < 1 || digits > 5) { status.textContent = 'digits must be >= 1 and <= 5'; return; } const trainingSizeLimit = Math.pow(Math.pow(10, digits), 2); if (trainingSize > trainingSizeLimit) { status.textContent = `With digits = ${digits}, you cannot have more than ` + `${trainingSizeLimit} examples`; return; } const demo = new AdditionRNNDemo(digits, trainingSize, rnnType, layers, hiddenSize); await demo.train(trainIterations, batchSize, numTestExamples); }); } runAdditionRNNDemo();
0
rapidsai_public_repos/node/modules/demo/tfjs
rapidsai_public_repos/node/modules/demo/tfjs/addition-rnn/README.md
# TensorFlow.js Example: Addition RNN A minimal standalone version of the [Addition RNN example](https://github.com/tensorflow/tfjs-examples/tree/d974c7ffa87416510c5978684bee5aa0715459db/addition-rnn) from the [tfjs-examples repository](https://github.com/tensorflow/tfjs-examples) running in node.
0
rapidsai_public_repos/node/modules/demo/tfjs
rapidsai_public_repos/node/modules/demo/tfjs/addition-rnn/app.js
// Copyright (c) 2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import chalk from 'chalk'; import * as tf from '@tensorflow/tfjs'; // Populate DOM with expected demo elements document.body.append( createElement('p', 'trainStatus'), createElement('div', 'lossChart'), createElement('div', 'accuracyChart'), createElement('p', 'testExamples'), createElement('button', 'trainModel'), createElement('input', 'digits', 2), createElement('input', 'trainingSize', 5000), createElement('select', 'rnnType'), createElement('input', 'rnnLayers', 1), createElement('input', 'rnnLayerSize', 128), createElement('input', 'batchSize', 128), createElement('input', 'trainIterations', 100), createElement('input', 'numTestExamples', 20), ); document.getElementById('rnnType').append( createElement('option', null, 'SimpleRNN'), createElement('option', null, 'GRU'), createElement('option', null, 'LSTM') ); document.getElementById('rnnType').selectedIndex = 0; // Listen for changes to `trainStatus` content and pipe to the console new MutationObserver((mutations, observer) => { console.clear(); console.log(mutations.map(({ addedNodes }) => Array.from(addedNodes).map((n) => n.textContent).join('\n') ).join('\n')); }).observe(document.getElementById('trainStatus'), {childList: true}); // Listen for changes to `testExamples` content and pipe to the console new MutationObserver((mutations, observer) => { console.log(mutations.map(({ addedNodes }) => Array.from(addedNodes) .filter(({ nodeName, classList }) => (nodeName === 'DIV') && (classList = Array.from(classList)) && (classList.includes('answer-wrong') || classList.includes('answer-correct'))) .map(({ textContent, classList }) => Array.from(classList).includes('answer-correct') ? chalk.green(textContent) : chalk.red(textContent)) .join('\n') ).join('\n')); }).observe(document.getElementById('testExamples'), {childList: true}); tf.env().set('WEBGL_VERSION', 2); tf.enableProdMode(); // Import and run the TFJS demo require('./demo'); // Start the TFJS demo training setTimeout(() => document .getElementById('trainModel') .dispatchEvent(new KeyboardEvent('click')), 100 ); function createElement(type, id, value) { const elt = document.createElement(type); if (arguments.length > 1 && id) elt.setAttribute('id', id); if (arguments.length > 2) elt.setAttribute('value', value); return elt; }
0
rapidsai_public_repos/node/modules/demo/tfjs
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests/test.js
// Copyright (c) 2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Silence internal TF.js "High memory usage..." const {MathBackendWebGL} = require('@tensorflow/tfjs-backend-webgl/dist/backend_webgl.js'); Object.defineProperty( MathBackendWebGL.prototype, 'warnedAboutMemory', {get() { return true; }, set() { /* noop */ }}); const Jasmine = require('jasmine'); const runner = new Jasmine(); require('@tensorflow/tfjs-core/dist/index.js'); require('@tensorflow/tfjs-backend-webgl/dist/index.js'); const {setTestEnvs, setupTestFilters} = require('@tensorflow/tfjs-core/dist/jasmine_util.js'); // Force WebGL2 setTestEnvs([{ name: 'webgl2', backendName: 'webgl', flags: { // 'DEBUG': true, // force DEBUG mode 'WEBGL_VERSION': 2, // 'WEBGL_CPU_FORWARD': false, // 'WEBGL_SIZE_UPLOAD_UNIFORM': 0, // 'WEBGL_RENDER_FLOAT32_ENABLED': true, // 'WEBGL_CHECK_NUMERICAL_PROBLEMS': false, }, isDataSync: true }]); setupTestFilters([], (testName) => { const toExclude = ['isBrowser: false', 'tensor in worker', 'dilation gradient']; for (const subStr of toExclude) { if (testName.includes(subStr)) { return false; } } return true; }); // // Import and run tfjs-core tests require('@tensorflow/tfjs-core/dist/tests.js'); // require('@tensorflow/tfjs-core/dist/io/io_utils_test.js'); // // Import and run tfjs-backend-webgl tests require('./test/backend_webgl_test.js'); require('./test/canvas_util_test.js'); require('./test/flags_webgl_test.js'); require('./test/gpgpu_context_test.js'); require('./test/gpgpu_util_test.js'); require('./test/Complex_test.js'); require('./test/Max_test.js'); require('./test/Mean_test.js'); require('./test/Reshape_test.js'); require('./test/STFT_test.js'); require('./test/reshape_packed_test.js'); require('./test/shader_compiler_util_test.js'); require('./test/tex_util_test.js'); require('./test/webgl_batchnorm_test.js'); require('./test/webgl_custom_op_test.js'); require('./test/webgl_ops_test.js'); require('./test/webgl_topixels_test.js'); require('./test/webgl_util_test.js'); module.exports = runner;
0
rapidsai_public_repos/node/modules/demo/tfjs
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests/package.json
{ "private": true, "name": "@rapidsai/demo-tfjs-webgl-tests", "main": "index.js", "version": "22.12.2", "license": "Apache-2.0", "author": "NVIDIA, Inc. (https://nvidia.com/)", "maintainers": [ "Paul Taylor <paul.e.taylor@me.com>" ], "bin": "index.js", "scripts": { "start": "node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js", "watch": "find -type f | entr -c -d -r node --experimental-vm-modules --enable-source-maps --trace-uncaught index.js" }, "dependencies": { "@rapidsai/glfw": "~22.12.2", "@tensorflow/tfjs": "2.8.6", "jasmine": "3.1.0", "jasmine-core": "3.1.0" }, "files": [ "test", "index.js", "package.json" ] }
0
rapidsai_public_repos/node/modules/demo/tfjs
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests/index.js
#!/usr/bin/env node // Copyright (c) 2021-2022, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. module.exports = () => { const {GLFWOpenGLProfile} = require('@rapidsai/glfw'); const {RapidsJSDOM} = require('@rapidsai/jsdom'); const jsdom = new RapidsJSDOM({ // Change cwd to the example dir so relative file paths are resolved // module: {path: __dirname}, module, glfwOptions: {openGLProfile: GLFWOpenGLProfile.COMPAT} }); jsdom.window.evalFn(() => { // Silence all internal TF.js warnings console.warn = () => {}; return require('./test').execute(); }); return jsdom; }; if (require.main === module) { // ensure tests are run with headless EGL delete process.env.DISPLAY; module.exports().window.addEventListener('close', () => process.exit(0), {once: true}); }
0
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests/test/tex_util_test.d.ts
/** * @license * Copyright 2017 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ export {};
0
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests/test/Reshape_test.js
/** * @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ import * as tf from '@tensorflow/tfjs-core'; import { test_util } from '@tensorflow/tfjs-core'; const { expectArraysClose, expectArraysEqual } = test_util; // tslint:disable-next-line: no-imports-from-dist import { describeWithFlags, ALL_ENVS } from '@tensorflow/tfjs-core/dist/jasmine_util'; describeWithFlags('Reshape.', ALL_ENVS, () => { it('does not have memory leak.', async () => { const beforeDataIds = tf.engine().backend.numDataIds(); const x = tf.tensor1d([1, 1, 1, 1]); const res = // tslint:disable-next-line: no-unnecessary-type-assertion tf.engine().runKernel('Reshape', { x }, { shape: [2, 2] }); expectArraysClose(await res.data(), [1, 1, 1, 1]); expectArraysEqual(res.shape, [2, 2]); const afterResDataIds = tf.engine().backend.numDataIds(); expect(afterResDataIds).toEqual(beforeDataIds + 1); x.dispose(); res.dispose(); const afterDisposeDataIds = tf.engine().backend.numDataIds(); expect(afterDisposeDataIds).toEqual(beforeDataIds); }); it('does not have memory leak calling reshape twice.', async () => { const beforeDataIds = tf.engine().backend.numDataIds(); // Adding 1 new dataId. const x = tf.tensor1d([1, 1, 1, 1]); // Does not add new dataId; const res = // tslint:disable-next-line: no-unnecessary-type-assertion tf.engine().runKernel('Reshape', { x }, { shape: [2, 2] }); expectArraysEqual(res.shape, [2, 2]); // Does not add new dataId. const res2 = // tslint:disable-next-line: no-unnecessary-type-assertion tf.engine().runKernel('Reshape', { x: res }, { shape: [1, 4] }); expectArraysEqual(res2.shape, [1, 4]); const afterRes2DataIds = tf.engine().backend.numDataIds(); expect(afterRes2DataIds).toEqual(beforeDataIds + 1); res.dispose(); const afterResDataIds = tf.engine().backend.numDataIds(); expect(afterResDataIds).toEqual(beforeDataIds + 1); x.dispose(); res2.dispose(); const afterDisposeDataIds = tf.engine().backend.numDataIds(); // Should be able to dispose the dataId. expect(afterDisposeDataIds).toEqual(beforeDataIds); }); it('does not leak when reshaping a shallowly sliced tensor', async () => { const packedFlagSaved = tf.env().getBool('WEBGL_PACK'); tf.env().set('WEBGL_PACK', false); const nBefore = tf.memory().numTensors; const nBeforeDataIds = tf.engine().backend.numDataIds(); const a = tf.tensor1d([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]); const b = tf.slice(a, 0, 6); await b.data(); let nAfter = tf.memory().numTensors; let nAfterDataIds = tf.engine().backend.numDataIds(); expect(nAfter).toBe(nBefore + 2); expect(nAfterDataIds).toBe(nBeforeDataIds + 2); const c = tf.reshape(b, [2, 3]); expectArraysClose(await c.data(), [0, 1, 2, 3, 4, 5]); tf.dispose([a, b]); nAfter = tf.memory().numTensors; nAfterDataIds = tf.engine().backend.numDataIds(); expect(nAfter).toBe(nBefore + 1); expect(nAfterDataIds).toBe(nBeforeDataIds + 1); tf.dispose([c]); nAfter = tf.memory().numTensors; nAfterDataIds = tf.engine().backend.numDataIds(); expect(nAfter).toBe(nBefore); expect(nAfterDataIds).toBe(nBeforeDataIds); tf.env().set('WEBGL_PACK', packedFlagSaved); }); }); //# sourceMappingURL=Reshape_test.js.map
0
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests/test/Complex_test.d.ts
/** * @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ export {};
0
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests/test/Max_test.d.ts
/** * @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ export {};
0
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests/test/Max_test.js
/** * @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ import * as tf from '@tensorflow/tfjs-core'; // tslint:disable-next-line: no-imports-from-dist import { ALL_ENVS, describeWithFlags } from '@tensorflow/tfjs-core/dist/jasmine_util'; describeWithFlags('Max', ALL_ENVS, () => { it('does not have memory leak when calling reduce multiple times.', async () => { const beforeDataIds = tf.engine().backend.numDataIds(); // Input must be large enough to trigger multi-stage reduction. const x = tf.ones([100, 100]); const xMax = x.max(); const afterResDataIds = tf.engine().backend.numDataIds(); expect(afterResDataIds).toEqual(beforeDataIds + 2); x.dispose(); xMax.dispose(); const afterDisposeDataIds = tf.engine().backend.numDataIds(); expect(afterDisposeDataIds).toEqual(beforeDataIds); }); }); //# sourceMappingURL=Max_test.js.map
0
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests/test/setup_test.d.ts
/** * @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ import '@tensorflow/tfjs-backend-cpu'; import '@tensorflow/tfjs-core/dist/public/chained_ops/register_all_chained_ops'; import '@tensorflow/tfjs-core/dist/register_all_gradients'; import './backend_webgl_test_registry'; import '@tensorflow/tfjs-core/dist/tests';
0
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests/test/flags_webgl_test.js
/** * @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ import * as tf from '@tensorflow/tfjs-core'; import { device_util } from '@tensorflow/tfjs-core'; // tslint:disable-next-line: no-imports-from-dist import { describeWithFlags } from '@tensorflow/tfjs-core/dist/jasmine_util'; import { WEBGL_ENVS } from '@tensorflow/tfjs-backend-webgl/dist/backend_webgl_test_registry'; import * as canvas_util from '@tensorflow/tfjs-backend-webgl/dist/canvas_util'; import { forceHalfFloat, webgl_util } from '@tensorflow/tfjs-backend-webgl/dist/webgl'; describe('WEBGL_FORCE_F16_TEXTURES', () => { afterAll(() => tf.env().reset()); it('can be activated via forceHalfFloat utility', () => { forceHalfFloat(); expect(tf.env().getBool('WEBGL_FORCE_F16_TEXTURES')).toBe(true); }); it('turns off WEBGL_RENDER_FLOAT32_ENABLED', () => { tf.env().reset(); forceHalfFloat(); expect(tf.env().getBool('WEBGL_RENDER_FLOAT32_ENABLED')).toBe(false); }); }); const RENDER_FLOAT32_ENVS = { flags: { 'WEBGL_RENDER_FLOAT32_CAPABLE': true }, predicate: WEBGL_ENVS.predicate }; const RENDER_FLOAT16_ENVS = { flags: { 'WEBGL_RENDER_FLOAT32_CAPABLE': false }, predicate: WEBGL_ENVS.predicate }; describeWithFlags('WEBGL_RENDER_FLOAT32_CAPABLE', RENDER_FLOAT32_ENVS, () => { beforeEach(() => { tf.env().reset(); }); afterAll(() => tf.env().reset()); it('should be independent of forcing f16 rendering', () => { forceHalfFloat(); expect(tf.env().getBool('WEBGL_RENDER_FLOAT32_CAPABLE')).toBe(true); }); it('if user is not forcing f16, device should render to f32', () => { expect(tf.env().getBool('WEBGL_RENDER_FLOAT32_ENABLED')).toBe(true); }); }); describeWithFlags('WEBGL_RENDER_FLOAT32_CAPABLE', RENDER_FLOAT16_ENVS, () => { beforeEach(() => { tf.env().reset(); }); afterAll(() => tf.env().reset()); it('should be independent of forcing f16 rendering', () => { forceHalfFloat(); expect(tf.env().getBool('WEBGL_RENDER_FLOAT32_CAPABLE')).toBe(false); }); it('should be reflected in WEBGL_RENDER_FLOAT32_ENABLED', () => { expect(tf.env().getBool('WEBGL_RENDER_FLOAT32_ENABLED')).toBe(false); }); }); describe('HAS_WEBGL', () => { beforeEach(() => tf.env().reset()); afterAll(() => tf.env().reset()); it('false when version is 0', () => { tf.env().set('WEBGL_VERSION', 0); expect(tf.env().getBool('HAS_WEBGL')).toBe(false); }); it('true when version is 1', () => { tf.env().set('WEBGL_VERSION', 1); expect(tf.env().getBool('HAS_WEBGL')).toBe(true); }); it('true when version is 2', () => { tf.env().set('WEBGL_VERSION', 2); expect(tf.env().getBool('HAS_WEBGL')).toBe(true); }); }); describe('WEBGL_PACK', () => { beforeEach(() => tf.env().reset()); afterAll(() => tf.env().reset()); it('true when HAS_WEBGL is true', () => { tf.env().set('HAS_WEBGL', true); expect(tf.env().getBool('WEBGL_PACK')).toBe(true); }); it('false when HAS_WEBGL is false', () => { tf.env().set('HAS_WEBGL', false); expect(tf.env().getBool('WEBGL_PACK')).toBe(false); }); }); describe('WEBGL_PACK_NORMALIZATION', () => { beforeEach(() => tf.env().reset()); afterAll(() => tf.env().reset()); it('true when WEBGL_PACK is true', () => { tf.env().set('WEBGL_PACK', true); expect(tf.env().getBool('WEBGL_PACK_NORMALIZATION')).toBe(true); }); it('false when WEBGL_PACK is false', () => { tf.env().set('WEBGL_PACK', false); expect(tf.env().getBool('WEBGL_PACK_NORMALIZATION')).toBe(false); }); }); describe('WEBGL_PACK_CLIP', () => { beforeEach(() => tf.env().reset()); afterAll(() => tf.env().reset()); it('true when WEBGL_PACK is true', () => { tf.env().set('WEBGL_PACK', true); expect(tf.env().getBool('WEBGL_PACK_CLIP')).toBe(true); }); it('false when WEBGL_PACK is false', () => { tf.env().set('WEBGL_PACK', false); expect(tf.env().getBool('WEBGL_PACK_CLIP')).toBe(false); }); }); // TODO: https://github.com/tensorflow/tfjs/issues/1679 // describe('WEBGL_PACK_DEPTHWISECONV', () => { // beforeEach(() => tf.env().reset()); // afterAll(() => tf.env().reset()); // it('true when WEBGL_PACK is true', () => { // tf.env().set('WEBGL_PACK', true); // expect(tf.env().getBool('WEBGL_PACK_DEPTHWISECONV')).toBe(true); // }); // it('false when WEBGL_PACK is false', () => { // tf.env().set('WEBGL_PACK', false); // expect(tf.env().getBool('WEBGL_PACK_DEPTHWISECONV')).toBe(false); // }); // }); describe('WEBGL_PACK_BINARY_OPERATIONS', () => { beforeEach(() => tf.env().reset()); afterAll(() => tf.env().reset()); it('true when WEBGL_PACK is true', () => { tf.env().set('WEBGL_PACK', true); expect(tf.env().getBool('WEBGL_PACK_BINARY_OPERATIONS')).toBe(true); }); it('false when WEBGL_PACK is false', () => { tf.env().set('WEBGL_PACK', false); expect(tf.env().getBool('WEBGL_PACK_BINARY_OPERATIONS')).toBe(false); }); }); describe('WEBGL_PACK_ARRAY_OPERATIONS', () => { beforeEach(() => tf.env().reset()); afterAll(() => tf.env().reset()); it('true when WEBGL_PACK is true', () => { tf.env().set('WEBGL_PACK', true); expect(tf.env().getBool('WEBGL_PACK_ARRAY_OPERATIONS')).toBe(true); }); it('false when WEBGL_PACK is false', () => { tf.env().set('WEBGL_PACK', false); expect(tf.env().getBool('WEBGL_PACK_ARRAY_OPERATIONS')).toBe(false); }); }); describe('WEBGL_PACK_IMAGE_OPERATIONS', () => { beforeEach(() => tf.env().reset()); afterAll(() => tf.env().reset()); it('true when WEBGL_PACK is true', () => { tf.env().set('WEBGL_PACK', true); expect(tf.env().getBool('WEBGL_PACK_IMAGE_OPERATIONS')).toBe(true); }); it('false when WEBGL_PACK is false', () => { tf.env().set('WEBGL_PACK', false); expect(tf.env().getBool('WEBGL_PACK_IMAGE_OPERATIONS')).toBe(false); }); }); describe('WEBGL_PACK_REDUCE', () => { beforeEach(() => tf.env().reset()); afterAll(() => tf.env().reset()); it('true when WEBGL_PACK is true', () => { tf.env().set('WEBGL_PACK', true); expect(tf.env().getBool('WEBGL_PACK_REDUCE')).toBe(true); }); it('false when WEBGL_PACK is false', () => { tf.env().set('WEBGL_PACK', false); expect(tf.env().getBool('WEBGL_PACK_REDUCE')).toBe(false); }); }); describe('WEBGL_LAZILY_UNPACK', () => { beforeEach(() => tf.env().reset()); afterAll(() => tf.env().reset()); it('true when WEBGL_PACK is true', () => { tf.env().set('WEBGL_PACK', true); expect(tf.env().getBool('WEBGL_LAZILY_UNPACK')).toBe(true); }); it('false when WEBGL_PACK is false', () => { tf.env().set('WEBGL_PACK', false); expect(tf.env().getBool('WEBGL_LAZILY_UNPACK')).toBe(false); }); }); describe('WEBGL_CONV_IM2COL', () => { beforeEach(() => tf.env().reset()); afterAll(() => tf.env().reset()); it('true when WEBGL_PACK is true', () => { tf.env().set('WEBGL_PACK', true); expect(tf.env().getBool('WEBGL_CONV_IM2COL')).toBe(true); }); it('false when WEBGL_PACK is false', () => { tf.env().set('WEBGL_PACK', false); expect(tf.env().getBool('WEBGL_CONV_IM2COL')).toBe(false); }); }); describe('WEBGL_MAX_TEXTURE_SIZE', () => { beforeEach(() => { tf.env().reset(); webgl_util.resetMaxTextureSize(); spyOn(canvas_util, 'getWebGLContext').and.returnValue({ MAX_TEXTURE_SIZE: 101, getParameter: (param) => { if (param === 101) { return 50; } throw new Error(`Got undefined param ${param}.`); } }); }); afterAll(() => { tf.env().reset(); webgl_util.resetMaxTextureSize(); }); it('is a function of gl.getParameter(MAX_TEXTURE_SIZE)', () => { expect(tf.env().getNumber('WEBGL_MAX_TEXTURE_SIZE')).toBe(50); }); }); describe('WEBGL_MAX_TEXTURES_IN_SHADER', () => { let maxTextures; beforeEach(() => { tf.env().reset(); webgl_util.resetMaxTexturesInShader(); spyOn(canvas_util, 'getWebGLContext').and.callFake(() => { return { MAX_TEXTURE_IMAGE_UNITS: 101, getParameter: (param) => { if (param === 101) { return maxTextures; } throw new Error(`Got undefined param ${param}.`); } }; }); }); afterAll(() => { tf.env().reset(); webgl_util.resetMaxTexturesInShader(); }); it('is a function of gl.getParameter(MAX_TEXTURE_IMAGE_UNITS)', () => { maxTextures = 10; expect(tf.env().getNumber('WEBGL_MAX_TEXTURES_IN_SHADER')).toBe(10); }); it('is capped at 16', () => { maxTextures = 20; expect(tf.env().getNumber('WEBGL_MAX_TEXTURES_IN_SHADER')).toBe(16); }); }); describe('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE', () => { beforeEach(() => tf.env().reset()); afterAll(() => tf.env().reset()); it('disjoint query timer disabled', () => { tf.env().set('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION', 0); expect(tf.env().getBool('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE')) .toBe(false); }); it('disjoint query timer enabled, mobile', () => { tf.env().set('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION', 1); spyOn(device_util, 'isMobile').and.returnValue(true); expect(tf.env().getBool('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE')) .toBe(false); }); it('disjoint query timer enabled, not mobile', () => { tf.env().set('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION', 1); spyOn(device_util, 'isMobile').and.returnValue(false); expect(tf.env().getBool('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE')) .toBe(true); }); }); describe('WEBGL_SIZE_UPLOAD_UNIFORM', () => { beforeEach(() => tf.env().reset()); afterAll(() => tf.env().reset()); it('is 0 when there is no float32 bit support', () => { tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', false); expect(tf.env().getNumber('WEBGL_SIZE_UPLOAD_UNIFORM')).toBe(0); }); it('is > 0 when there is float32 bit support', () => { tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true); expect(tf.env().getNumber('WEBGL_SIZE_UPLOAD_UNIFORM')).toBeGreaterThan(0); }); }); describeWithFlags('WEBGL_DELETE_TEXTURE_THRESHOLD', WEBGL_ENVS, () => { it('should throw an error if given a negative value', () => { expect(() => tf.env().set('WEBGL_DELETE_TEXTURE_THRESHOLD', -2)).toThrow(); }); }); //# sourceMappingURL=flags_webgl_test.js.map
0
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests/test/shader_compiler_util_test.js
/** * @license * Copyright 2018 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ // tslint:disable-next-line: no-imports-from-dist import { describeWithFlags } from '@tensorflow/tfjs-core/dist/jasmine_util'; import { WEBGL_ENVS } from '@tensorflow/tfjs-backend-webgl/dist/backend_webgl_test_registry'; import { dotify, getLogicalCoordinatesFromFlatIndex } from '@tensorflow/tfjs-backend-webgl/dist/shader_compiler_util'; describeWithFlags('shader compiler', WEBGL_ENVS, () => { it('dotify takes two arrays of coordinates and produces' + 'the glsl that finds the dot product of those coordinates', () => { const coords1 = ['r', 'g', 'b', 'a']; const coords2 = ['x', 'y', 'z', 'w']; expect(dotify(coords1, coords2)) .toEqual('dot(vec4(r,g,b,a), vec4(x,y,z,w))'); }); it('dotify should split up arrays into increments of vec4s', () => { const coords1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g']; const coords2 = ['h', 'i', 'j', 'k', 'l', 'm', 'n']; expect(dotify(coords1, coords2)) .toEqual('dot(vec4(a,b,c,d), vec4(h,i,j,k))+dot(vec3(e,f,g), vec3(l,m,n))'); }); it('getLogicalCoordinatesFromFlatIndex produces glsl that takes' + 'a flat index and finds its coordinates within that shape', () => { const coords = ['r', 'c', 'd']; const shape = [1, 2, 3]; expect(getLogicalCoordinatesFromFlatIndex(coords, shape)) .toEqual('int r = index / 6; index -= r * 6;' + 'int c = index / 3; int d = index - c * 3;'); }); }); //# sourceMappingURL=shader_compiler_util_test.js.map
0
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests/test/canvas_util_test.js
/** * @license * Copyright 2018 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ import * as tf from '@tensorflow/tfjs-core'; // tslint:disable-next-line: no-imports-from-dist import { BROWSER_ENVS, describeWithFlags } from '@tensorflow/tfjs-core/dist/jasmine_util'; import { getWebGLContext } from '@tensorflow/tfjs-backend-webgl/dist/canvas_util'; describeWithFlags('canvas_util', BROWSER_ENVS, () => { it('Returns a valid canvas', () => { const canvas = getWebGLContext(tf.env().getNumber('WEBGL_VERSION')).canvas; expect((canvas instanceof HTMLCanvasElement) || (canvas instanceof OffscreenCanvas)) .toBe(true); }); it('Returns a valid gl context', () => { const gl = getWebGLContext(tf.env().getNumber('WEBGL_VERSION')); expect(gl.isContextLost()).toBe(false); }); }); describeWithFlags('canvas_util webgl2', { flags: { WEBGL_VERSION: 2 } }, () => { it('is ok when the user requests webgl 1 canvas', () => { const canvas = getWebGLContext(1).canvas; expect(canvas.getContext != null).toBe(true); }); }); //# sourceMappingURL=canvas_util_test.js.map
0
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests/test/STFT_test.js
/** * @license * Copyright 2021 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ import * as tf from '@tensorflow/tfjs-core'; // tslint:disable-next-line: no-imports-from-dist import { ALL_ENVS, describeWithFlags } from '@tensorflow/tfjs-core/dist/jasmine_util'; describeWithFlags('stft memory test', ALL_ENVS, () => { it('should have no mem leak', async () => { const win = 320; const fft = 320; const hop = 160; const input = tf.zeros([1760]); const startTensors = tf.memory().numTensors; const startDataIds = tf.engine().backend.numDataIds(); const result = await tf.signal.stft(input, win, hop, fft); // 1 new tensor, 3 new data buckets. expect(tf.memory().numTensors).toBe(startTensors + 1); expect(tf.engine().backend.numDataIds()).toBe(startTensors + 3); result.dispose(); // Zero net tensors / data buckets. expect(tf.memory().numTensors).toBe(startTensors); expect(tf.engine().backend.numDataIds()).toBe(startDataIds); input.dispose(); }); }); //# sourceMappingURL=STFT_test.js.map
0
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests/test/gpgpu_util_test.d.ts
/** * @license * Copyright 2017 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ export {};
0
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests/test/webgl_util_test.d.ts
/** * @license * Copyright 2017 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ export {};
0
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests/test/Reshape_test.d.ts
/** * @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ export {};
0
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests/test/webgl_batchnorm_test.d.ts
/** * @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ export {};
0
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests/test/shader_compiler_util_test.d.ts
/** * @license * Copyright 2018 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ export {};
0
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests/test/webgl_topixels_test.d.ts
/** * @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ export {};
0
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests/test/webgl_ops_test.js
/** * @license * Copyright 2017 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ import { test_util } from '@tensorflow/tfjs-core'; const expectArraysClose = test_util.expectArraysClose; const expectArraysEqual = test_util.expectArraysEqual; // tslint:disable-next-line: no-imports-from-dist import { describeWithFlags } from '@tensorflow/tfjs-core/dist/jasmine_util'; import * as tf from '@tensorflow/tfjs-core'; import { PACKED_ENVS, WEBGL_ENVS } from '@tensorflow/tfjs-backend-webgl/dist/backend_webgl_test_registry'; describeWithFlags('fromPixels + regular math op', WEBGL_ENVS, () => { it('fromPixels + add', async () => { const pixels = new ImageData(2, 2); for (let i = 0; i < 8; i++) { pixels.data[i] = 100; } for (let i = 8; i < 16; i++) { pixels.data[i] = 250; } const a = tf.browser.fromPixels(pixels, 4); const b = tf.scalar(20, 'int32'); const res = tf.add(a, b); expectArraysEqual(await res.data(), [ 120, 120, 120, 120, 120, 120, 120, 120, 270, 270, 270, 270, 270, 270, 270, 270 ]); }); }); describeWithFlags('toPixels', WEBGL_ENVS, () => { it('draws a rank-2 float32 tensor, canvas', done => { const x = tf.tensor2d([.15, .2], [2, 1], 'float32'); const canvas = document.createElement('canvas'); tf.browser.toPixels(x, canvas).then(data => { const expected = new Uint8ClampedArray([ Math.round(.15 * 255), Math.round(.15 * 255), Math.round(.15 * 255), 255, Math.round(.2 * 255), Math.round(.2 * 255), Math.round(.2 * 255), 255 ]); expect(data).toEqual(expected); const ctx = canvas.getContext('2d'); const imgData = ctx.getImageData(0, 0, 1, 2); expect(imgData.data).toEqual(expected); done(); }); }); it('draws a rank-2 int32 tensor, canvas', done => { const x = tf.tensor2d([10, 20], [2, 1], 'int32'); const canvas = document.createElement('canvas'); tf.browser.toPixels(x, canvas).then(data => { const expected = new Uint8ClampedArray([10, 10, 10, 255, 20, 20, 20, 255]); expect(data).toEqual(expected); const ctx = canvas.getContext('2d'); const imgData = ctx.getImageData(0, 0, 1, 2); expect(imgData.data).toEqual(expected); done(); }); }); it('draws a rank-3 float32 tensor, 1 channel, canvas', done => { const x = tf.tensor3d([.15, .2], [2, 1, 1], 'float32'); const canvas = document.createElement('canvas'); tf.browser.toPixels(x, canvas).then(data => { const expected = new Uint8ClampedArray([ Math.round(.15 * 255), Math.round(.15 * 255), Math.round(.15 * 255), 255, Math.round(.2 * 255), Math.round(.2 * 255), Math.round(.2 * 255), 255 ]); expect(data).toEqual(expected); const ctx = canvas.getContext('2d'); const imgData = ctx.getImageData(0, 0, 1, 2); expect(imgData.data).toEqual(expected); done(); }); }); it('draws a rank-3 int32 tensor, 1 channel, canvas', done => { const x = tf.tensor3d([10, 20], [2, 1, 1], 'int32'); const canvas = document.createElement('canvas'); tf.browser.toPixels(x, canvas).then(data => { const expected = new Uint8ClampedArray([10, 10, 10, 255, 20, 20, 20, 255]); expect(data).toEqual(expected); const ctx = canvas.getContext('2d'); const imgData = ctx.getImageData(0, 0, 1, 2); expect(imgData.data).toEqual(expected); done(); }); }); it('draws a rank-3 float32 tensor, 3 channel, canvas', done => { const x = tf.tensor3d([.05, .1001, .15, .20, .25, .3001], [2, 1, 3], 'float32'); const canvas = document.createElement('canvas'); tf.browser.toPixels(x, canvas).then(data => { const expected = new Uint8ClampedArray([ Math.round(.05 * 255), Math.round(.1001 * 255), Math.round(.15 * 255), 255, Math.round(.2 * 255), Math.round(.25 * 255), Math.round(.3001 * 255), 255 ]); expect(data).toEqual(expected); const ctx = canvas.getContext('2d'); const imgData = ctx.getImageData(0, 0, 1, 2); expect(imgData.data).toEqual(expected); done(); }); }); it('draws a rank-3 int32 tensor, 3 channel, canvas', done => { const x = tf.tensor3d([10, 20, 30, 40, 50, 60], [2, 1, 3], 'int32'); const canvas = document.createElement('canvas'); tf.browser.toPixels(x, canvas).then(data => { const expected = new Uint8ClampedArray([10, 20, 30, 255, 40, 50, 60, 255]); expect(data).toEqual(expected); const ctx = canvas.getContext('2d'); const imgData = ctx.getImageData(0, 0, 1, 2); expect(imgData.data).toEqual(expected); done(); }); }); it('draws a rank-3 float32 tensor, 4 channel, canvas', done => { // ImageData roundtrips are lossy because of pre-multiplied alphas, so we // use an alpha = 1 to avoid losing precision on r, g, b channels in these // tests https://www.w3.org/TR/2dcontext/ const x = tf.tensor3d([.05, .1001, .15, 1, .20, .25, .3001, 1], [2, 1, 4], 'float32'); const canvas = document.createElement('canvas'); tf.browser.toPixels(x, canvas).then(data => { const expected = new Uint8ClampedArray([ Math.round(.05 * 255), Math.round(.1001 * 255), Math.round(.15 * 255), 255, Math.round(.20 * 255), Math.round(.25 * 255), Math.round(.3001 * 255), 255 ]); expect(data).toEqual(expected); const ctx = canvas.getContext('2d'); const imgData = ctx.getImageData(0, 0, 1, 2); expect(imgData.data).toEqual(expected); done(); }); }); it('draws a rank-3 int32 tensor, 4 channel, canvas', done => { // ImageData roundtrips are lossy because of pre-multiplied alphas, so we // use an alpha = 1 to avoid losing precision on r, g, b channels in these // tests https://www.w3.org/TR/2dcontext/ const x = tf.tensor3d([10, 20, 30, 255, 50, 60, 70, 255], [2, 1, 4], 'int32'); const canvas = document.createElement('canvas'); tf.browser.toPixels(x, canvas).then(data => { const expected = new Uint8ClampedArray([10, 20, 30, 255, 50, 60, 70, 255]); expect(data).toEqual(expected); const ctx = canvas.getContext('2d'); const imgData = ctx.getImageData(0, 0, 1, 2); expect(imgData.data).toEqual(expected); done(); }); }); it('accepts a tensor-like object', async () => { const x = [[127], [100]]; // 2x1; const canvas = document.createElement('canvas'); const data = await tf.browser.toPixels(x, canvas); const expected = new Uint8ClampedArray([127, 127, 127, 255, 100, 100, 100, 255]); expect(data).toEqual(expected); const ctx = canvas.getContext('2d'); const imgData = ctx.getImageData(0, 0, 1, 2); expect(imgData.data).toEqual(expected); }); }); describeWithFlags('depthToSpace', WEBGL_ENVS, () => { it('tensor4d, input shape=[1, 4, 1, 1], blockSize=2, format=NCHW', async () => { const t = tf.tensor4d([1, 2, 3, 4], [1, 4, 1, 1]); const blockSize = 2; const dataFormat = 'NCHW'; const res = tf.depthToSpace(t, blockSize, dataFormat); expect(res.shape).toEqual([1, 1, 2, 2]); expectArraysClose(await res.data(), [1, 2, 3, 4]); }); it('tensor4d, input shape=[1, 12, 1, 1], blockSize=2, format=NCHW', async () => { const t = tf.tensor4d([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], [1, 12, 1, 1]); const blockSize = 2; const dataFormat = 'NCHW'; const res = tf.depthToSpace(t, blockSize, dataFormat); expect(res.shape).toEqual([1, 3, 2, 2]); expectArraysClose(await res.data(), [1, 4, 7, 10, 2, 5, 8, 11, 3, 6, 9, 12]); }); it('tensor4d, input shape=[1, 4, 2, 2], blockSize=2, format=NCHW', async () => { const t = tf.tensor4d([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], [1, 4, 2, 2]); const blockSize = 2; const dataFormat = 'NCHW'; const res = tf.depthToSpace(t, blockSize, dataFormat); expect(res.shape).toEqual([1, 1, 4, 4]); expectArraysClose(await res.data(), [1, 5, 2, 6, 9, 13, 10, 14, 3, 7, 4, 8, 11, 15, 12, 16]); }); it('tensor4d, input shape=[1, 8, 2, 2], blockSize=2, format=NCHW', async () => { const t = tf.tensor4d([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32 ], [1, 8, 2, 2]); const blockSize = 2; const dataFormat = 'NCHW'; const res = tf.depthToSpace(t, blockSize, dataFormat); expect(res.shape).toEqual([1, 2, 4, 4]); expectArraysClose(await res.data(), [ 1, 9, 2, 10, 17, 25, 18, 26, 3, 11, 4, 12, 19, 27, 20, 28, 5, 13, 6, 14, 21, 29, 22, 30, 7, 15, 8, 16, 23, 31, 24, 32 ]); }); }); describeWithFlags('maximum', WEBGL_ENVS, () => { it('works with squarification for large dimension', async () => { const maxTextureSize = tf.env().getNumber('WEBGL_MAX_TEXTURE_SIZE'); tf.env().set('WEBGL_MAX_TEXTURE_SIZE', 5); const a = tf.tensor2d([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], [2, 7]); const b = tf.tensor2d([-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], [2, 7]); const result = tf.maximum(a, b); tf.env().set('WEBGL_MAX_TEXTURE_SIZE', maxTextureSize); expectArraysClose(await result.data(), [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]); }); }); describeWithFlags('div', PACKED_ENVS, () => { it('works when unused channels are divided', async () => { // Tests that the 0's in unused channels for input textures do not corrupt // the result when swizzled with 3 / 3. const a = tf.tensor2d([1], [1, 1]); const b = tf.tensor2d([1], [1, 1]); const c = tf.add(a, b).div(a); const d = tf.add(a, b).div(a); const result = c.matMul(d); expectArraysClose(await result.data(), [4]); }); it('works when unused channels in tensors with size > 1 are divided', async () => { const a = tf.tensor2d([1, 2, 3], [3, 1]); const b = tf.tensor2d([1, 2, 3], [3, 1]); const c = a.div(b); const d = tf.tensor1d([1, 2, 3]); const e = tf.tensor1d([1, 2, 3]); const f = d.div(e).reshape([1, 3]); const result = c.matMul(f); expectArraysClose(await result.data(), [1, 1, 1, 1, 1, 1, 1, 1, 1]); }); }); describeWithFlags('conv2d webgl', WEBGL_ENVS, () => { it('packed input x=[2,1,2] f=[1,1,2,2] s=1 d=1 p=0', async () => { const inputShape = [2, 1, 2]; const fSize = 1; const pad = 0; const stride = 1; const x = tf.tensor3d([1, 2, 3, 4], inputShape); const w = tf.tensor4d([1, 2, 3, 4], [fSize, fSize, 2, 2]); const webglLazilyUnpackFlagSaved = tf.env().getBool('WEBGL_LAZILY_UNPACK'); tf.env().set('WEBGL_LAZILY_UNPACK', true); const webglPackBinaryOperationsFlagSaved = tf.env().getBool('WEBGL_PACK_BINARY_OPERATIONS'); tf.env().set('WEBGL_PACK_BINARY_OPERATIONS', true); // First conv2D tests conv2D with non-packed input |x|, and the second uses // packed input |result|. const result = tf.conv2d(x, w, stride, pad); const result1 = tf.conv2d(result, w, stride, pad); tf.env().set('WEBGL_LAZILY_UNPACK', webglLazilyUnpackFlagSaved); tf.env().set('WEBGL_PACK_BINARY_OPERATIONS', webglPackBinaryOperationsFlagSaved); expectArraysClose(await result.data(), [7, 10, 15, 22]); expectArraysClose(await result1.data(), [37, 54, 81, 118]); }); it('tf.memory() packed input x=[1,1,1,2] f=[1,1,2,2] s=1 d=1 p=0', async () => { const startNumBytesInGPU = tf.memory().numBytesInGPU; const startNumBytes = tf.memory().numBytes; const inputShape = [1, 1, 1, 2]; const fSize = 1; const pad = 0; const stride = 1; const xInit = tf.tensor4d([0, 1], inputShape); const w = tf.tensor4d([1, 2, 3, 4], [fSize, fSize, 2, 2]); const webglLazilyUnpackFlagSaved = tf.env().getBool('WEBGL_LAZILY_UNPACK'); tf.env().set('WEBGL_LAZILY_UNPACK', true); const webglPackBinaryOperationsFlagSaved = tf.env().getBool('WEBGL_PACK_BINARY_OPERATIONS'); tf.env().set('WEBGL_PACK_BINARY_OPERATIONS', true); const x = xInit.add(1); const result = tf.conv2d(x, w, stride, pad); tf.env().set('WEBGL_LAZILY_UNPACK', webglLazilyUnpackFlagSaved); tf.env().set('WEBGL_PACK_BINARY_OPERATIONS', webglPackBinaryOperationsFlagSaved); expectArraysClose(await result.data(), [7, 10]); result.dispose(); x.dispose(); xInit.dispose(); w.dispose(); expect(tf.memory().numBytesInGPU - startNumBytesInGPU) .toBe(0); expect(tf.memory().numBytes - startNumBytes).toBe(0); }); }); describeWithFlags('conv to matmul', PACKED_ENVS, () => { it('im2col should not leak memory', () => { const inputDepth = 1; const inputShape = [2, 2, inputDepth]; const outputDepth = 1; const fSize = 2; const pad = 0; const stride = 1; const dataFormat = 'NHWC'; const dilation = 1; const x = tf.tensor3d([1, 2, 3, 4], inputShape); const w = tf.tensor4d([3, 1, 5, 0], [fSize, fSize, inputDepth, outputDepth]); const startNumBytes = tf.memory().numBytes; tf.conv2d(x, w, stride, pad, dataFormat, dilation); const endNumBytes = tf.memory().numBytes; expect(endNumBytes - startNumBytes).toEqual(4); }); it('pointwise conv should work when matmul is unpacked', () => { const inputDepth = 1001; // this number must be greater than MATMUL_SHARED_DIM_THRESHOLD // for matmul to be unpacked const inputShape = [3, 3, inputDepth]; const outputDepth = 1; const fSize = 1; const pad = 'same'; const stride = [1, 1]; let x = tf.randomNormal(inputShape); x = x.add(1); // this packs x so we can test the case where we mistakenly // want to avoid expensive reshape in pointwise conv2d even // though matmul is unpacked const w = tf.randomNormal([fSize, fSize, inputDepth, outputDepth]); expect(() => tf.conv2d(x, w, stride, pad)).not.toThrow(); }); }); // For operations on non-trivial matrix sizes, we skip the CPU-only ENV and use // only WebGL ENVs. describeWithFlags('gramSchmidt-non-tiny', WEBGL_ENVS, () => { it('8x16', async () => { // Part of this test's point is that operation on a matrix of this size // can complete in the timeout limit of the unit test. const xs = tf.randomUniform([8, 16]); const y = tf.linalg.gramSchmidt(xs); const yTransposed = y.transpose(); expectArraysClose(await y.matMul(yTransposed).data(), await tf.eye(8).data()); }); }); describeWithFlags('matmul webgl-only', WEBGL_ENVS, () => { it('Matrix times vector, large matrix', async () => { const maxTexSize = 16000; const sharedDim = maxTexSize + 4; const matrix = tf.buffer([2, sharedDim], 'float32'); matrix.set(1, 0, sharedDim - 3); matrix.set(1, 0, sharedDim - 2); const v = tf.buffer([sharedDim], 'float32'); v.set(1, sharedDim - 3); v.set(1, sharedDim - 2); const result = tf.dot(matrix.toTensor(), v.toTensor()); const expected = [2, 0]; expectArraysClose(await result.data(), expected); }); }); describeWithFlags('matmul', PACKED_ENVS, () => { it('should not leak memory', () => { const a = tf.tensor2d([1, 2, 3, 4, 5, 6, 7, 8, 9], [3, 3]); const b = tf.tensor2d([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], [3, 5]); const startNumBytes = tf.memory().numBytes; tf.matMul(a, b); const endNumBytes = tf.memory().numBytes; expect(endNumBytes - startNumBytes).toEqual(60); }); it('should work when input matrix dimensions are not divisible by 2', async () => { const a = tf.tensor2d([1, 2, 3, 4, 5, 6, 7, 8, 9], [3, 3]); const b = tf.tensor2d([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], [3, 5]); const c = tf.matMul(a, b); expect(c.shape).toEqual([3, 5]); expectArraysClose(await c.data(), [ 46, 52, 58, 64, 70, 100, 115, 130, 145, 160, 154, 178, 202, 226, 250 ]); }); it('should work when output texture shape != physical shape', async () => { const sharedDim = 16000; const a = tf.buffer([2, sharedDim], 'float32'); const b = tf.buffer([sharedDim, 2], 'float32'); a.set(1, 0, sharedDim - 1); a.set(1, 0, sharedDim - 2); a.set(1, 1, sharedDim - 1); b.set(1, sharedDim - 1, 0); b.set(1, sharedDim - 2, 0); const c = tf.matMul(a.toTensor(), b.toTensor()); const expected = [2, 0, 1, 0]; expectArraysClose(await c.data(), expected); }); it('should work when input texture shapes != physical shape', async () => { const maxTextureSize = tf.env().getNumber('WEBGL_MAX_TEXTURE_SIZE'); tf.env().set('WEBGL_MAX_TEXTURE_SIZE', 5); const a = tf.tensor2d([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11], [1, 12]); const b = tf.tensor2d([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], [12, 1]); const c = tf.matMul(a, b); tf.env().set('WEBGL_MAX_TEXTURE_SIZE', maxTextureSize); expectArraysClose(await c.data(), [572]); }); it('should work when squarification results in zero padding', async () => { const maxTextureSize = tf.env().getNumber('WEBGL_MAX_TEXTURE_SIZE'); tf.env().set('WEBGL_MAX_TEXTURE_SIZE', 3); const a = tf.tensor2d([1, 2], [1, 2]); const b = tf.tensor2d([[0, 1, 2, 3, 4, 5, 6, 7, 8], [9, 10, 11, 12, 13, 14, 15, 16, 17]]); const c = tf.matMul(a, b); tf.env().set('WEBGL_MAX_TEXTURE_SIZE', maxTextureSize); expectArraysClose(await c.data(), [18, 21, 24, 27, 30, 33, 36, 39, 42]); }); it('A x B', async () => { const a = tf.tensor2d([1, 2, 3, 4, 5, 6], [2, 3]); const b = tf.tensor2d([0, 1, -3, 2, 2, 1], [3, 2]); const c = tf.matMul(a, b); expect(c.shape).toEqual([2, 2]); expectArraysClose(await c.data(), [0, 8, -3, 20]); }); it('A x B^t', async () => { const a = tf.tensor2d([1, 2, 3, 4, 5, 6], [2, 3]); const b = tf.tensor2d([1, 0, 2, 4, 3, 0], [2, 3]); const transposeA = false; const transposeB = true; const c = tf.matMul(a, b, transposeA, transposeB); const expected = [7, 10, 16, 31]; expectArraysClose(await c.data(), expected); }); it('A^t x B', async () => { const a = tf.tensor2d([1, 2, 3, 4, 5, 6], [2, 3]); const b = tf.tensor2d([1, 0, 2, 4, 3, 0], [2, 3]); const transposeA = true; const transposeB = false; const c = tf.matMul(a, b, transposeA, transposeB); const expected = [17, 12, 2, 22, 15, 4, 27, 18, 6]; expectArraysClose(await c.data(), expected); }); it('A^t x B^t', async () => { const a = tf.tensor2d([1, 2, 3, 4, 5, 6], [3, 2]); const b = tf.tensor2d([1, 0, 2, 4, 3, 0], [2, 3]); const transposeA = true; const transposeB = true; const c = tf.matMul(a, b, transposeA, transposeB); const expected = [11, 13, 14, 20]; expectArraysClose(await c.data(), expected); }); it('works when followed by an op that requires unpacked inputs', async () => { const a = tf.tensor2d([1, 2, 3, 4, 5, 6], [2, 3]); const b = tf.tensor2d([0, 1, -3, 2, 2, 1], [3, 2]); const c = tf.matMul(a, b); const webglPackBinarySaved = tf.env().getBool('WEBGL_PACK_BINARY_OPERATIONS'); tf.env().set('WEBGL_PACK_BINARY_OPERATIONS', false); const d = tf.add(c, 1); tf.env().set('WEBGL_PACK_BINARY_OPERATIONS', webglPackBinarySaved); expectArraysClose(await d.data(), [1, 9, -2, 21]); }); // tslint:disable-next-line:max-line-length it('works when followed by a packed reshape that changes texture layout, and then an unpacked op', async () => { const a = tf.tensor2d([1, 2, 3, 4, 5, 6, 7, 8, 9], [9, 1]); const b = tf.tensor2d([1], [1, 1]); const c = tf.matMul(a, b); const d = tf.reshape(c, [1, 3, 3, 1]); const webglPackBinarySaved = tf.env().getBool('WEBGL_PACK_BINARY_OPERATIONS'); tf.env().set('WEBGL_PACK_BINARY_OPERATIONS', false); const e = tf.add(d, 1); tf.env().set('WEBGL_PACK_BINARY_OPERATIONS', webglPackBinarySaved); expectArraysClose(await e.data(), [2, 3, 4, 5, 6, 7, 8, 9, 10]); }); it('works when preceded by an op that requires packed inputs', async () => { const a = tf.tensor2d([1, 2, 3, 4, 5, 6], [2, 3]); const b = tf.tensor2d([0, 1, -3, 2, 2, 1], [3, 2]); const c = tf.add(a, 1); const d = tf.matMul(b, c); expectArraysClose(await d.data(), [5, 6, 7, 4, 3, 2, 9, 12, 15]); }); }); describeWithFlags('Reduction: webgl packed input', WEBGL_ENVS, () => { it('argmax 3D, odd number of rows, axis = -1', async () => { const webglLazilyUnpackFlagSaved = tf.env().getBool('WEBGL_LAZILY_UNPACK'); tf.env().set('WEBGL_LAZILY_UNPACK', true); const webglPackBinaryOperationsFlagSaved = tf.env().getBool('WEBGL_PACK_BINARY_OPERATIONS'); tf.env().set('WEBGL_PACK_BINARY_OPERATIONS', true); const a = tf.tensor3d([3, 2, 5, 100, -7, 2], [2, 1, 3]).add(1); const r = tf.argMax(a, -1); tf.env().set('WEBGL_LAZILY_UNPACK', webglLazilyUnpackFlagSaved); tf.env().set('WEBGL_PACK_BINARY_OPERATIONS', webglPackBinaryOperationsFlagSaved); expect(r.dtype).toBe('int32'); expectArraysEqual(await r.data(), [2, 0]); }); it('argmin 4D, odd number of rows, axis = -1', async () => { const webglLazilyUnpackFlagSaved = tf.env().getBool('WEBGL_LAZILY_UNPACK'); tf.env().set('WEBGL_LAZILY_UNPACK', true); const webglPackBinaryOperationsFlagSaved = tf.env().getBool('WEBGL_PACK_BINARY_OPERATIONS'); tf.env().set('WEBGL_PACK_BINARY_OPERATIONS', true); const a = tf.tensor4d([3, 2, 5, 100, -7, 2, 8, 7, -5, 101, 7, -2, 100, -7, 2, 8, 7, -5], [1, 2, 3, 3]) .add(1); const r = tf.argMin(a, -1); tf.env().set('WEBGL_LAZILY_UNPACK', webglLazilyUnpackFlagSaved); tf.env().set('WEBGL_PACK_BINARY_OPERATIONS', webglPackBinaryOperationsFlagSaved); expect(r.dtype).toBe('int32'); expectArraysEqual(await r.data(), [1, 1, 2, 2, 1, 2]); }); it('should not leak memory when called after unpacked op', async () => { const webglPackBinaryOperationsFlagSaved = tf.env().getBool('WEBGL_PACK_BINARY_OPERATIONS'); tf.env().set('WEBGL_PACK_BINARY_OPERATIONS', false); const a = tf.tensor5d([3, 2, 5, 100, -7, 2, 8, 7, -5, 101, 7, -2, 100, -7, 2, 8, 7, -5], [1, 2, 3, 1, 3]) .add(1); const startNumBytes = tf.memory().numBytes; const startNumTensors = tf.memory().numTensors; const r = tf.argMin(a, -1); tf.env().set('WEBGL_PACK_BINARY_OPERATIONS', webglPackBinaryOperationsFlagSaved); const endNumBytes = tf.memory().numBytes; const endNumTensors = tf.memory().numTensors; expect(endNumBytes - startNumBytes).toEqual(24); expect(endNumTensors - startNumTensors).toEqual(1); expect(r.dtype).toBe('int32'); expectArraysEqual(await r.data(), [1, 1, 2, 2, 1, 2]); }); }); describeWithFlags('slice and memory usage', WEBGL_ENVS, () => { beforeAll(() => { tf.env().set('WEBGL_CPU_FORWARD', false); tf.env().set('WEBGL_SIZE_UPLOAD_UNIFORM', 0); }); it('slice a tensor, read it and check memory', async () => { const getMem = () => tf.memory(); expect(getMem().numBytesInGPU).toBe(0); // Lazy upload won't increase gpu memory. const a = tf.tensor([2, 3]); expect(getMem().numBytesInGPU).toBe(0); // Upload a to the GPU by running an op. a.square().dispose(); expect(getMem().numBytesInGPU).toBe(8); // Slicing does not allocate new memory. const b = a.slice(0); expect(getMem().numBytesInGPU).toBe(8); // Download a to the CPU but the texture remains on GPU // since b points to it. await a.data(); expect(getMem().numBytesInGPU).toBe(8); // Dispose a, but the texture should still remain on the GPU // since b points to it. a.dispose(); expect(getMem().numBytesInGPU).toBe(8); // Dispose b and expect 0 memory on GPU. b.dispose(); expect(getMem().numBytesInGPU).toBe(0); }); }); describeWithFlags('slice a packed texture', WEBGL_ENVS, () => { beforeAll(() => { tf.env().set('WEBGL_PACK', true); }); it('slice after a matmul', async () => { const a = [[1, 2], [3, 4]]; const b = [[5, 6], [7, 8]]; // Matmul gives a packed tensor in webgl. // [19, 22] // [43, 50] const c = tf.matMul(a, b); expectArraysClose(await c.slice([0, 0]).data(), [19, 22, 43, 50]); expectArraysClose(await c.slice([0, 1]).data(), [22, 50]); expectArraysClose(await c.slice([1, 0]).data(), [43, 50]); expectArraysClose(await c.slice([1, 1]).data(), [50]); }); }); describeWithFlags('pointwise conv2d packed', WEBGL_ENVS, () => { beforeAll(() => { tf.env().set('WEBGL_SIZE_UPLOAD_UNIFORM', 0); }); it('pointwise conv2d optimization with odd input size', async () => { // We do special optimization in the webl backend which avoids an expensive // reshape, when the following 3 conditions are met: // 1) the input width/height is odd-shaped. // 2) the input is already packed. // 3) the filter size is 1x1, i.e. pointwise. const inChannels = 1; const outChannels = 2; const oddInputSize = 3; const x = tf.ones([oddInputSize, oddInputSize, inChannels]); const xPacked = tf.relu(x); const pointwiseFilter = tf.ones([1, 1, inChannels, outChannels]); const strides = 1; const pad = 'same'; const c = tf.conv2d(xPacked, pointwiseFilter, strides, pad); expectArraysClose(await c.data(), [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]); }); }); describeWithFlags('relu', WEBGL_ENVS, () => { it('works with squarification for prime number length vector', async () => { const maxTextureSize = tf.env().getNumber('WEBGL_MAX_TEXTURE_SIZE'); tf.env().set('WEBGL_MAX_TEXTURE_SIZE', 5); const a = tf.tensor1d([1, -2, 5, -3, -1, 4, 7]); const result = tf.relu(a); tf.env().set('WEBGL_MAX_TEXTURE_SIZE', maxTextureSize); expectArraysClose(await result.data(), [1, 0, 5, 0, 0, 4, 7]); }); }); describeWithFlags('packed clip', PACKED_ENVS, () => { it('should not leak memory', () => { const a = tf.tensor1d([3, -1, 0, 100, -7, 2]); const min = -1; const max = 50; const startNumBytes = tf.memory().numBytes; const startNumTensors = tf.memory().numTensors; tf.clipByValue(a, min, max); const endNumBytes = tf.memory().numBytes; const endNumTensors = tf.memory().numTensors; expect(endNumBytes - startNumBytes).toEqual(24); expect(endNumTensors - startNumTensors).toEqual(1); }); it('basic', async () => { const a = tf.tensor1d([3, -1, 0, 100, -7, 2]); const min = -1; const max = 50; const result = tf.clipByValue(a, min, max); expectArraysClose(await result.data(), [3, -1, 0, 50, -1, 2]); }); it('using extreme values', async () => { const a = tf.tensor1d([3, -1, 0, 100, -7, 2]); let result = tf.clipByValue(a, Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY); expectArraysClose(await result.data(), [3, -1, 0, 100, -7, 2]); result = tf.clipByValue(a, Number.MIN_VALUE, Number.MAX_VALUE); expectArraysClose(await result.data(), [3, Number.MIN_VALUE, Number.MIN_VALUE, 100, Number.MIN_VALUE, 2]); }); it('should work for scalars', async () => { const a = tf.scalar(-4); const min = -1; const max = 50; const result = tf.clipByValue(a, min, max); expectArraysClose(await result.data(), [min]); }); it('derivative: 1D tensor with max or min value', async () => { const min = -1; const max = 2; const x = tf.tensor1d([-1, 1, 2, 3]); const dy = tf.tensor1d([1, 10, 100, 1000]); const gradients = tf.grad(x => x.clipByValue(min, max))(x, dy); expect(gradients.shape).toEqual(x.shape); expect(gradients.dtype).toEqual('float32'); expectArraysClose(await gradients.data(), [1, 10, 100, 0]); }); }); describeWithFlags('depthwiseConv2d packed', PACKED_ENVS, () => { it('should not leak memory', () => { const x = tf.tensor4d([ 0.230664, 0.987388, 0.0685208, 0.419224, 0.887861, 0.731641, 0.0741907, 0.409265, 0.351377 ], [1, 3, 3, 1]); const w = tf.tensor4d([0.303873, 0.229223, 0.144333, 0.803373], [2, 2, 1, 1]); const startNumBytes = tf.memory().numBytes; const startNumTensors = tf.memory().numTensors; tf.depthwiseConv2d(x, w, 1, 'valid'); const endNumBytes = tf.memory().numBytes; const endNumTensors = tf.memory().numTensors; expect(endNumBytes - startNumBytes).toEqual(16); expect(endNumTensors - startNumTensors).toEqual(1); }); }); //# sourceMappingURL=webgl_ops_test.js.map
0
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests/test/webgl_batchnorm_test.js
/** * @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ import * as tf from '@tensorflow/tfjs-core'; import { test_util } from '@tensorflow/tfjs-core'; const { expectArraysClose } = test_util; // tslint:disable-next-line: no-imports-from-dist import { describeWithFlags } from '@tensorflow/tfjs-core/dist/jasmine_util'; import { PACKED_ENVS, WEBGL_ENVS } from '@tensorflow/tfjs-backend-webgl/dist/backend_webgl_test_registry'; describeWithFlags('batchNorm', WEBGL_ENVS, () => { it('should work for broadcasted inputs', async () => { const x = tf.tensor4d([2, 4, 9, 23], [2, 1, 1, 2]); const mean = tf.tensor4d([1], [1, 1, 1, 1]); const variance = tf.tensor4d([1], [1, 1, 1, 1]); const result = tf.batchNorm4d(x, mean, variance); expectArraysClose(await result.data(), [0.9995003, 2.9985011, 7.9960027, 21.9890079]); }); it('should work when squarification results in zero padding', async () => { const maxTextureSize = tf.env().getNumber('WEBGL_MAX_TEXTURE_SIZE'); tf.env().set('WEBGL_MAX_TEXTURE_SIZE', 5); const x = tf.tensor3d([ 0.49955603, 0.04158615, -1.09440524, 2.03854165, -0.61578344, 2.87533573, 1.18105987, 0.807462, 1.87888837, 2.26563962, -0.37040935, 1.35848753, -0.75347094, 0.15683117, 0.91925946, 0.34121279, 0.92717143, 1.89683965 ], [2, 3, 3]); const mean = tf.tensor1d([0.39745062, -0.48062894, 0.4847822]); const variance = tf.tensor1d([0.32375343, 0.67117643, 1.08334653]); const offset = tf.tensor1d([0.69398749, -1.29056387, 0.9429723]); const scale = tf.tensor1d([-0.5607271, 0.9878457, 0.25181573]); const varianceEpsilon = .001; const result = tf.batchNorm3d(x, mean, variance, offset, scale, varianceEpsilon); tf.env().set('WEBGL_MAX_TEXTURE_SIZE', maxTextureSize); expectArraysClose(await result.data(), [ 0.59352049, -0.66135202, 0.5610874, -0.92077015, -1.45341019, 1.52106473, -0.07704776, 0.26144429, 1.28010017, -1.14422404, -1.15776136, 1.15425493, 1.82644104, -0.52249442, 1.04803919, 0.74932291, 0.40568101, 1.2844412 ]); }); }); describeWithFlags('batchnorm packed', PACKED_ENVS, () => { it('should not leak memory', () => { const x = tf.tensor4d([2, 4, 9, 23], [2, 1, 1, 2]); const mean = tf.tensor1d([1, 2]); const variance = tf.tensor1d([2, 3]); const varianceEpsilon = .001; const startNumBytes = tf.memory().numBytes; const startNumTensors = tf.memory().numTensors; tf.batchNorm4d(x, mean, variance, undefined, undefined, varianceEpsilon); const endNumBytes = tf.memory().numBytes; const endNumTensors = tf.memory().numTensors; expect(endNumBytes - startNumBytes).toEqual(16); expect(endNumTensors - startNumTensors).toEqual(1); }); }); //# sourceMappingURL=webgl_batchnorm_test.js.map
0
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests/test/webgl_ops_test.d.ts
/** * @license * Copyright 2017 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ export {};
0
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests/test/webgl_topixels_test.js
/** * @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ import * as tf from '@tensorflow/tfjs-core'; // tslint:disable-next-line: no-imports-from-dist import { describeWithFlags } from '@tensorflow/tfjs-core/dist/jasmine_util'; import { WEBGL_ENVS } from '@tensorflow/tfjs-backend-webgl/dist/backend_webgl_test_registry'; describeWithFlags('toPixels', WEBGL_ENVS, () => { it('does not leak memory', async () => { const x = tf.tensor2d([[.1], [.2]], [2, 1]); const startNumBytesInGPU = tf.memory().numBytesInGPU; await tf.browser.toPixels(x); expect(tf.memory().numBytesInGPU) .toEqual(startNumBytesInGPU); }); it('does not leak memory given a tensor-like object', async () => { const x = [[10], [20]]; // 2x1; const startNumBytesInGPU = tf.memory().numBytesInGPU; await tf.browser.toPixels(x); expect(tf.memory().numBytesInGPU) .toEqual(startNumBytesInGPU); }); }); //# sourceMappingURL=webgl_topixels_test.js.map
0
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests/test/webgl_custom_op_test.js
/** * @license * Copyright 2018 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ import * as tf from '@tensorflow/tfjs-core'; import { engine, test_util } from '@tensorflow/tfjs-core'; // tslint:disable-next-line: no-imports-from-dist import { describeWithFlags } from '@tensorflow/tfjs-core/dist/jasmine_util'; import { WEBGL_ENVS } from '@tensorflow/tfjs-backend-webgl/dist/backend_webgl_test_registry'; describeWithFlags('custom-op webgl', WEBGL_ENVS, () => { class SquareAndAddKernel { constructor(inputShape) { this.variableNames = ['X']; this.outputShape = inputShape.slice(); this.userCode = ` void main() { float x = getXAtOutCoords(); float value = x * x + x; setOutput(value); } `; } } class SquareAndAddBackpropKernel { constructor(inputShape) { this.variableNames = ['X']; this.outputShape = inputShape.slice(); this.userCode = ` void main() { float x = getXAtOutCoords(); float value = 2.0 * x + 1.0; setOutput(value); } `; } } function squareAndAdd(x) { const fn = tf.customGrad((x, save) => { save([x]); const webglBackend = tf.backend(); const program = new SquareAndAddKernel(x.shape); const backpropProgram = new SquareAndAddBackpropKernel(x.shape); const outInfo = webglBackend.compileAndRun(program, [x]); const value = engine().makeTensorFromDataId(outInfo.dataId, outInfo.shape, outInfo.dtype); const gradFunc = (dy, saved) => { const [x] = saved; const backInfo = webglBackend.compileAndRun(backpropProgram, [x]); const back = engine().makeTensorFromDataId(backInfo.dataId, backInfo.shape, backInfo.dtype); return back.mul(dy); }; return { value, gradFunc }; }); return fn(x); } it('lets users use custom operations', async () => { const inputArr = [1, 2, 3, 4]; const input = tf.tensor(inputArr); const output = squareAndAdd(input); test_util.expectArraysClose(await output.data(), inputArr.map(x => x * x + x)); }); it('lets users define gradients for operations', async () => { const inputArr = [1, 2, 3, 4]; const input = tf.tensor(inputArr); const grads = tf.valueAndGrad(x => squareAndAdd(x)); const { value, grad } = grads(input); test_util.expectArraysClose(await value.data(), inputArr.map(x => x * x + x)); test_util.expectArraysClose(await grad.data(), inputArr.map(x => 2 * x + 1)); }); it('multiplies by dy parameter when it is passed', async () => { const inputArr = [1, 2, 3, 4]; const input = tf.tensor(inputArr); const grads = tf.valueAndGrad(x => squareAndAdd(x)); const { value, grad } = grads(input, tf.zerosLike(input)); test_util.expectArraysClose(await value.data(), inputArr.map(x => x * x + x)); test_util.expectArraysClose(await grad.data(), inputArr.map(() => 0.0)); }); }); //# sourceMappingURL=webgl_custom_op_test.js.map
0
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests/test/gpgpu_context_test.js
/** * @license * Copyright 2017 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ import * as tf from '@tensorflow/tfjs-core'; // tslint:disable-next-line: no-imports-from-dist import { describeWithFlags } from '@tensorflow/tfjs-core/dist/jasmine_util'; import { WEBGL_ENVS } from '@tensorflow/tfjs-backend-webgl/dist/backend_webgl_test_registry'; import * as canvas_util from '@tensorflow/tfjs-backend-webgl/dist/canvas_util'; import { getGlslDifferences } from '@tensorflow/tfjs-backend-webgl/dist/glsl_version'; import { GPGPUContext, linearSearchLastTrue } from '@tensorflow/tfjs-backend-webgl/dist/gpgpu_context'; import * as tex_util from '@tensorflow/tfjs-backend-webgl/dist/tex_util'; const DOWNLOAD_FLOAT_ENVS = { flags: { 'WEBGL_DOWNLOAD_FLOAT_ENABLED': true }, predicate: WEBGL_ENVS.predicate }; describeWithFlags('GPGPUContext setOutputMatrixTexture', DOWNLOAD_FLOAT_ENVS, () => { let gpgpu; let texture; let gl; beforeEach(() => { canvas_util.clearWebGLContext(tf.env().getNumber('WEBGL_VERSION')); gl = canvas_util.getWebGLContext(tf.env().getNumber('WEBGL_VERSION')); gpgpu = new GPGPUContext(gl); // Silences debug warnings. spyOn(console, 'warn'); tf.enableDebugMode(); }); afterEach(() => { if (texture != null) { gpgpu.deleteMatrixTexture(texture); } gpgpu.dispose(); }); it('sets the output texture property to the output texture', () => { texture = gpgpu.createFloat32MatrixTexture(1, 1); gpgpu.setOutputMatrixTexture(texture, 1, 1); expect(gpgpu.outputTexture).toBe(texture); }); it('sets the gl viewport to the output texture dimensions', () => { const columns = 456; const rows = 123; texture = gpgpu.createFloat32MatrixTexture(rows, columns); gpgpu.setOutputMatrixTexture(texture, rows, columns); const expected = new Int32Array([0, 0, columns, rows]); expect(gpgpu.gl.getParameter(gpgpu.gl.VIEWPORT)).toEqual(expected); }); }); describeWithFlags('GPGPUContext setOutputPackedMatrixTexture', DOWNLOAD_FLOAT_ENVS, () => { let gpgpu; let texture; let gl; beforeEach(() => { canvas_util.clearWebGLContext(tf.env().getNumber('WEBGL_VERSION')); gl = canvas_util.getWebGLContext(tf.env().getNumber('WEBGL_VERSION')); gpgpu = new GPGPUContext(gl); // Silences debug warnings. spyOn(console, 'warn'); tf.enableDebugMode(); }); afterEach(() => { if (texture != null) { gpgpu.deleteMatrixTexture(texture); } gpgpu.dispose(); }); it('sets the output texture property to the output texture', () => { texture = gpgpu.createPackedMatrixTexture(1, 1); gpgpu.setOutputPackedMatrixTexture(texture, 1, 1); expect(gpgpu.outputTexture).toBe(texture); }); it('sets the gl viewport to the output packed texture dimensions', () => { const columns = 456; const rows = 123; texture = gpgpu.createPackedMatrixTexture(rows, columns); gpgpu.setOutputPackedMatrixTexture(texture, rows, columns); const [width, height] = tex_util.getPackedMatrixTextureShapeWidthHeight(rows, columns); const expected = new Int32Array([0, 0, width, height]); expect(gpgpu.gl.getParameter(gpgpu.gl.VIEWPORT)).toEqual(expected); }); }); describeWithFlags('GPGPUContext setOutputMatrixWriteRegion', DOWNLOAD_FLOAT_ENVS, () => { let gpgpu; let program; let output; beforeEach(() => { gpgpu = new GPGPUContext(); // Silences debug warnings. spyOn(console, 'warn'); tf.enableDebugMode(); const glsl = getGlslDifferences(); const src = `${glsl.version} precision highp float; ${glsl.defineOutput} void main() { ${glsl.output} = vec4(2,0,0,0); } `; program = gpgpu.createProgram(src); output = gpgpu.createFloat32MatrixTexture(4, 4); gpgpu.uploadDenseMatrixToTexture(output, 4, 4, new Float32Array(16)); gpgpu.setOutputMatrixTexture(output, 4, 4); gpgpu.setProgram(program); }); afterEach(() => { gpgpu.deleteMatrixTexture(output); gpgpu.deleteProgram(program); gpgpu.dispose(); }); it('sets the scissor box to the requested parameters', () => { gpgpu.setOutputMatrixWriteRegion(0, 1, 2, 3); const scissorBox = gpgpu.gl.getParameter(gpgpu.gl.SCISSOR_BOX); expect(scissorBox[0]).toEqual(2); expect(scissorBox[1]).toEqual(0); expect(scissorBox[2]).toEqual(3); expect(scissorBox[3]).toEqual(1); }); }); describeWithFlags('GPGPUContext', DOWNLOAD_FLOAT_ENVS, () => { let gpgpu; beforeEach(() => { gpgpu = new GPGPUContext(); // Silences debug warnings. spyOn(console, 'warn'); tf.enableDebugMode(); }); afterEach(() => { gpgpu.dispose(); }); it('throws an error if used after dispose', () => { const gpgpuContext = new GPGPUContext(); gpgpuContext.dispose(); expect(gpgpuContext.dispose).toThrowError(); }); it('throws an error if validation is on and framebuffer incomplete', () => { const glsl = getGlslDifferences(); const src = `${glsl.version} precision highp float; void main() {} `; const program = gpgpu.createProgram(src); const result = gpgpu.createFloat32MatrixTexture(1, 1); gpgpu.setOutputMatrixTexture(result, 1, 1); gpgpu.setProgram(program); gpgpu.deleteMatrixTexture(result); expect(gpgpu.executeProgram).toThrowError(); gpgpu.deleteProgram(program); }); }); describe('gpgpu_context linearSearchLastTrue', () => { it('[false]', () => { const a = [false]; const arr = a.map(x => () => x); expect(linearSearchLastTrue(arr)).toBe(-1); }); it('[true]', () => { const a = [true]; const arr = a.map(x => () => x); expect(linearSearchLastTrue(arr)).toBe(0); }); it('[false, false]', () => { const a = [false, false]; const arr = a.map(x => () => x); expect(linearSearchLastTrue(arr)).toBe(-1); }); it('[true, false]', () => { const a = [true, false]; const arr = a.map(x => () => x); expect(linearSearchLastTrue(arr)).toBe(0); }); it('[true, true]', () => { const a = [true, true]; const arr = a.map(x => () => x); expect(linearSearchLastTrue(arr)).toBe(1); }); it('[false, false, false]', () => { const a = [false, false, false]; const arr = a.map(x => () => x); expect(linearSearchLastTrue(arr)).toBe(-1); }); it('[true, false, false]', () => { const a = [true, false, false]; const arr = a.map(x => () => x); expect(linearSearchLastTrue(arr)).toBe(0); }); it('[true, true, false]', () => { const a = [true, true, false]; const arr = a.map(x => () => x); expect(linearSearchLastTrue(arr)).toBe(1); }); it('[true, true, true]', () => { const a = [true, true, true]; const arr = a.map(x => () => x); expect(linearSearchLastTrue(arr)).toBe(2); }); it('[false, false, false, false]', () => { const a = [false, false, false, false]; const arr = a.map(x => () => x); expect(linearSearchLastTrue(arr)).toBe(-1); }); it('[true, false, false, false]', () => { const a = [true, false, false, false]; const arr = a.map(x => () => x); expect(linearSearchLastTrue(arr)).toBe(0); }); it('[true, true, false, false]', () => { const a = [true, true, false, false]; const arr = a.map(x => () => x); expect(linearSearchLastTrue(arr)).toBe(1); }); it('[true, true, true, false]', () => { const a = [true, true, true, false]; const arr = a.map(x => () => x); expect(linearSearchLastTrue(arr)).toBe(2); }); it('[true, true, true, true]', () => { const a = [true, true, true, true]; const arr = a.map(x => () => x); expect(linearSearchLastTrue(arr)).toBe(3); }); }); //# sourceMappingURL=gpgpu_context_test.js.map
0
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests/test/gpgpu_context_test.d.ts
/** * @license * Copyright 2017 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ export {};
0
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests/test/reshape_packed_test.d.ts
/** * @license * Copyright 2018 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ export {};
0
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests/test/backend_webgl_test.d.ts
/** * @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ export {};
0
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests/test/reshape_packed_test.js
/** * @license * Copyright 2018 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ import * as tf from '@tensorflow/tfjs-core'; import { test_util } from '@tensorflow/tfjs-core'; const { expectArraysClose } = test_util; // tslint:disable-next-line: no-imports-from-dist import { describeWithFlags } from '@tensorflow/tfjs-core/dist/jasmine_util'; import { PACKED_ENVS } from '@tensorflow/tfjs-backend-webgl/dist/backend_webgl_test_registry'; describeWithFlags('expensive reshape', PACKED_ENVS, () => { const cValues = [46, 52, 58, 64, 70, 100, 115, 130, 145, 160, 154, 178, 202, 226, 250]; let c; beforeEach(() => { const a = tf.tensor2d([1, 2, 3, 4, 5, 6, 7, 8, 9], [3, 3]); const b = tf.tensor2d([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], [3, 5]); c = tf.matMul(a, b); }); it('6d --> 1d', async () => { const cAs6D = tf.reshape(c, [1, 1, 1, 3, 1, 5]); const cAs1D = tf.reshape(cAs6D, [-1, cValues.length]); expectArraysClose(await cAs1D.data(), cValues); }); it('1d --> 2d', async () => { const cAs1D = tf.reshape(c, [cValues.length]); const cAs2D = tf.reshape(cAs1D, [5, -1]); expectArraysClose(await cAs2D.data(), cValues); }); it('2d --> 3d', async () => { const cAs3D = tf.reshape(c, [3, 1, 5]); expectArraysClose(await cAs3D.data(), cValues); }); it('3d --> 4d', async () => { const cAs3D = tf.reshape(c, [3, 1, 5]); const cAs4D = tf.reshape(cAs3D, [3, 5, 1, 1]); expectArraysClose(await cAs4D.data(), cValues); }); it('4d --> 5d', async () => { const cAs4D = tf.reshape(c, [3, 5, 1, 1]); const cAs5D = tf.reshape(cAs4D, [1, 1, 1, 5, 3]); expectArraysClose(await cAs5D.data(), cValues); }); it('5d --> 6d', async () => { const cAs5D = tf.reshape(c, [1, 1, 1, 5, 3]); const cAs6D = tf.reshape(cAs5D, [3, 5, 1, 1, 1, 1]); expectArraysClose(await cAs6D.data(), cValues); }); }); describeWithFlags('expensive reshape with even columns', PACKED_ENVS, () => { it('2 --> 4 columns', async () => { const maxTextureSize = tf.env().getNumber('WEBGL_MAX_TEXTURE_SIZE'); let values = new Array(16).fill(0); values = values.map((d, i) => i + 1); const a = tf.tensor2d(values, [8, 2]); const b = tf.tensor2d([1, 2, 3, 4], [2, 2]); tf.env().set('WEBGL_MAX_TEXTURE_SIZE', 2); // Setting WEBGL_MAX_TEXTURE_SIZE to 2 makes that [8, 2] tensor is packed // to texture of width 2 by height 2. Indices are packed as: // ------------- // | 0 1 | 4 5 | // First row's four // | 2 3 | 6 7 | // pixels. // ------------- // ... const c = tf.matMul(a, b); let cAs4D = c.reshape([2, 1, 2, 4]); tf.env().set('WEBGL_MAX_TEXTURE_SIZE', maxTextureSize); // Execute non-packed operations to unpack tensor. const webglPackFlagSaved = tf.env().getBool('WEBGL_PACK'); tf.env().set('WEBGL_PACK', false); cAs4D = cAs4D.add(1); cAs4D = cAs4D.add(-1); tf.env().set('WEBGL_PACK', webglPackFlagSaved); const result = [7, 10, 15, 22, 23, 34, 31, 46, 39, 58, 47, 70, 55, 82, 63, 94]; expectArraysClose(await cAs4D.data(), result); }); }); //# sourceMappingURL=reshape_packed_test.js.map
0
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests/test/setup_test.js
/** * @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ import '@tensorflow/tfjs-backend-cpu'; // tslint:disable-next-line: no-imports-from-dist import '@tensorflow/tfjs-core/dist/public/chained_ops/register_all_chained_ops'; // tslint:disable-next-line: no-imports-from-dist import '@tensorflow/tfjs-core/dist/register_all_gradients'; import '@tensorflow/tfjs-backend-webgl/dist/backend_webgl_test_registry'; // tslint:disable-next-line: no-imports-from-dist import { parseTestEnvFromKarmaFlags, setTestEnvs, setupTestFilters, TEST_ENVS } from '@tensorflow/tfjs-core/dist/jasmine_util'; const TEST_FILTERS = []; const customInclude = (testName) => { const toExclude = ['isBrowser: false', 'tensor in worker', 'dilation gradient']; for (const subStr of toExclude) { if (testName.includes(subStr)) { return false; } } return true; }; setupTestFilters(TEST_FILTERS, customInclude); if (typeof __karma__ !== 'undefined') { const testEnv = parseTestEnvFromKarmaFlags(__karma__.config.args, TEST_ENVS); if (testEnv != null) { setTestEnvs([testEnv]); } } // Import and run tests from core. // tslint:disable-next-line:no-imports-from-dist import '@tensorflow/tfjs-core/dist/tests'; //# sourceMappingURL=setup_test.js.map
0
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests/test/webgl_custom_op_test.d.ts
/** * @license * Copyright 2018 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ export {};
0
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests/test/flags_webgl_test.d.ts
/** * @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ export {};
0
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests/test/STFT_test.d.ts
/** * @license * Copyright 2021 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ export {};
0
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests/test/canvas_util_test.d.ts
export {};
0
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests/test/backend_webgl_test.js
/** * @license * Copyright 2019 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ import * as tf from '@tensorflow/tfjs-core'; import { engine, test_util, util } from '@tensorflow/tfjs-core'; // tslint:disable-next-line: no-imports-from-dist import { describeWithFlags } from '@tensorflow/tfjs-core/dist/jasmine_util'; const { expectArraysClose, expectArraysEqual } = test_util; const { decodeString } = util; import { getBinaryCache, MathBackendWebGL } from '@tensorflow/tfjs-backend-webgl/dist/backend_webgl'; import { computeBytes } from '@tensorflow/tfjs-backend-webgl/dist/texture_manager'; import { PhysicalTextureType } from '@tensorflow/tfjs-backend-webgl/dist/tex_util'; import { WEBGL_ENVS } from '@tensorflow/tfjs-backend-webgl/dist/backend_webgl_test_registry'; import { GPGPUContext } from '@tensorflow/tfjs-backend-webgl/dist/gpgpu_context'; function decodeStrings(bytes) { return bytes.map(b => decodeString(b)); } const RENDER_FLOAT32_ENVS = { flags: { 'WEBGL_RENDER_FLOAT32_ENABLED': true }, predicate: WEBGL_ENVS.predicate }; describeWithFlags('forced f16 render', RENDER_FLOAT32_ENVS, () => { beforeAll(() => { tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', false); }); xit('should overflow if larger than 66k', async () => { const a = tf.tensor1d([Math.pow(2, 17)], 'float32'); const b = tf.relu(a); expect(await b.data()).toBeLessThan(Math.pow(2, 17)); }); it('should error in debug mode', () => { // Silence debug warnings. spyOn(console, 'warn'); tf.enableDebugMode(); const a = () => tf.tensor1d([2, Math.pow(2, 17)], 'float32'); expect(a).toThrowError(); }); }); describeWithFlags('lazy packing and unpacking', WEBGL_ENVS, () => { let webglLazilyUnpackFlagSaved; let webglCpuForwardFlagSaved; beforeAll(() => { webglLazilyUnpackFlagSaved = tf.env().getBool('WEBGL_LAZILY_UNPACK'); webglCpuForwardFlagSaved = tf.env().getBool('WEBGL_CPU_FORWARD'); tf.env().set('WEBGL_LAZILY_UNPACK', true); tf.env().set('WEBGL_CPU_FORWARD', false); }); afterAll(() => { tf.env().set('WEBGL_LAZILY_UNPACK', webglLazilyUnpackFlagSaved); tf.env().set('WEBGL_CPU_FORWARD', webglCpuForwardFlagSaved); }); it('should not leak memory when lazily unpacking', () => { const a = tf.tensor2d([1, 2, 3, 4, 5, 6], [2, 3]); const b = tf.tensor2d([0, 1, -3, 2, 2, 1], [3, 2]); // c is packed to 1x1 RGBA texture. const c = tf.matMul(a, b); const startNumBytes = tf.memory().numBytes; const startNumTensors = tf.memory().numTensors; const startNumBytesInGPU = tf.memory().numBytesInGPU; const webglPackBinaryOperationsFlagSaved = tf.env().getBool('WEBGL_PACK_BINARY_OPERATIONS'); tf.env().set('WEBGL_PACK_BINARY_OPERATIONS', false); // Add will unpack c before the operation to 2 tf.add(c, 1); tf.env().set('WEBGL_PACK_BINARY_OPERATIONS', webglPackBinaryOperationsFlagSaved); expect(tf.memory().numBytes - startNumBytes).toEqual(16); expect(tf.memory().numTensors - startNumTensors).toEqual(1); // result is unpacked 2x2 R texture. expect(tf.memory().numBytesInGPU - startNumBytesInGPU) .toEqual(4 * tf.util.bytesPerElement(a.dtype)); }); it('should not leak memory when lazily packing', () => { const a = tf.tensor2d([1, 2, 3, 4, 5, 6], [2, 3]); const b = tf.tensor2d([0, 1, -3, 2, 2, 1], [3, 2]); const c = tf.add(a, 1); const startNumBytes = tf.memory().numBytes; const startNumTensors = tf.memory().numTensors; const startNumBytesInGPU = tf.memory().numBytesInGPU; tf.matMul(b, c); expect(tf.memory().numBytes - startNumBytes).toEqual(36); expect(tf.memory().numTensors - startNumTensors).toEqual(1); // result [3, 3] is packed to four RGBA pixel texture b is packed to two // RGBA texels texture: total 6 * 4 = 24 components. expect(tf.memory().numBytesInGPU - startNumBytesInGPU) .toEqual(24 * tf.util.bytesPerElement(a.dtype)); }); it('should work when the same input must be represented by' + 'different textures', async () => { const a = tf.tensor1d([1, 2]); const res = tf.dot(a, a); expectArraysClose(await res.data(), [5]); }); }); describeWithFlags('backendWebGL', WEBGL_ENVS, () => { let prevBackend; beforeAll(() => { prevBackend = tf.getBackend(); }); afterEach(() => { tf.setBackend(prevBackend); tf.removeBackend('test-storage'); }); it('register string tensor with values', () => { const backend = new MathBackendWebGL(); tf.registerBackend('test-storage', () => backend); tf.setBackend('test-storage'); const t = engine().makeTensor(['a', 'b', 'c'], [3], 'string'); expectArraysEqual(decodeStrings(backend.readSync(t.dataId)), ['a', 'b', 'c']); }); it('register string tensor with values and wrong shape throws error', () => { const backend = new MathBackendWebGL(); tf.registerBackend('test-storage', () => backend); tf.setBackend('test-storage'); expect(() => tf.tensor(['a', 'b', 'c'], [4], 'string')).toThrowError(); }); it('reading', () => { const backend = new MathBackendWebGL(null); tf.registerBackend('test-storage', () => backend); tf.setBackend('test-storage'); const texManager = backend.getTextureManager(); const t = engine().makeTensor(new Float32Array([1, 2, 3]), [3], 'float32'); expect(texManager.getNumUsedTextures()).toBe(0); backend.getTexture(t.dataId); expect(texManager.getNumUsedTextures()).toBe(1); expectArraysClose(backend.readSync(t.dataId), new Float32Array([1, 2, 3])); expect(texManager.getNumUsedTextures()).toBe(0); backend.getTexture(t.dataId); expect(texManager.getNumUsedTextures()).toBe(1); backend.disposeData(t.dataId); expect(texManager.getNumUsedTextures()).toBe(0); }); it('read packed and then use by an unpacked op', async () => { const backend = new MathBackendWebGL(null); tf.registerBackend('test-storage', () => backend); tf.copyRegisteredKernels('webgl', 'test-storage'); tf.setBackend('test-storage'); const webglPackFlagSaved = tf.env().getBool('WEBGL_PACK'); tf.env().set('WEBGL_PACK', true); const webglSizeUploadUniformSaved = tf.env().getNumber('WEBGL_SIZE_UPLOAD_UNIFORM'); tf.env().set('WEBGL_SIZE_UPLOAD_UNIFORM', 0); const a = tf.tensor2d([1, 2], [2, 1]); const b = tf.tensor2d([1], [1, 1]); const c = tf.matMul(a, b); backend.readSync(c.dataId); tf.env().set('WEBGL_PACK', false); const d = tf.add(c, 1); tf.env().set('WEBGL_PACK', webglPackFlagSaved); tf.env().set('WEBGL_SIZE_UPLOAD_UNIFORM', webglSizeUploadUniformSaved); expectArraysClose(await d.data(), [2, 3]); }); it('delayed storage, overwriting', () => { const backend = new MathBackendWebGL(null); tf.registerBackend('test-storage', () => backend); tf.setBackend('test-storage'); const texManager = backend.getTextureManager(); const t = engine().makeTensor(new Float32Array([1, 2, 3]), [3], 'float32'); backend.getTexture(t.dataId); expect(texManager.getNumUsedTextures()).toBe(1); expectArraysClose(backend.readSync(t.dataId), new Float32Array([1, 2, 3])); backend.getTexture(t.dataId); expect(texManager.getNumUsedTextures()).toBe(1); expectArraysClose(backend.readSync(t.dataId), new Float32Array([1, 2, 3])); expect(texManager.getNumUsedTextures()).toBe(0); }); }); describeWithFlags('Webgl backend disposal', WEBGL_ENVS, () => { it('register and dispose a backend outside unit test', () => { // Simulate outside unit test environment. tf.ENV.set('IS_TEST', false); const backend = new MathBackendWebGL(); tf.registerBackend('test-disposal', () => backend); tf.copyRegisteredKernels('webgl', 'test-disposal'); tf.setBackend('test-disposal'); // Compile and run a program. tf.zeros([1000]).sqrt().dataSync(); // Dispose the backend. tf.backend().dispose(); // Make sure the cache is empty. const cache = getBinaryCache(tf.ENV.getNumber('WEBGL_VERSION')); expect(Object.keys(cache).length).toBe(0); tf.removeBackend('test-disposal'); }); it('register and dispose a backend inside unit test', () => { // Simulate inside unit test environment. tf.ENV.set('IS_TEST', true); const backend = new MathBackendWebGL(); tf.registerBackend('test-disposal', () => backend); tf.copyRegisteredKernels('webgl', 'test-disposal'); tf.setBackend('test-disposal'); // Compile and run a program. tf.zeros([1000]).sqrt().dataSync(); // Dispose the backend. tf.backend().dispose(); // Make sure the cache is NOT empty. const cache = getBinaryCache(tf.ENV.getNumber('WEBGL_VERSION')); expect(Object.keys(cache).length).toBeGreaterThan(0); tf.removeBackend('test-disposal'); }); it('register, dispose and re-register a backend outside unit test', () => { // Simulate outside unit test environment. tf.ENV.set('IS_TEST', false); tf.registerBackend('test-disposal', () => new MathBackendWebGL()); tf.copyRegisteredKernels('webgl', 'test-disposal'); tf.setBackend('test-disposal'); // Compile and run a program. tf.zeros([1000]).sqrt().dataSync(); // Dispose the backend. tf.backend().dispose(); tf.removeBackend('test-disposal'); // Re-register a backend. tf.registerBackend('test-disposal', () => new MathBackendWebGL()); tf.copyRegisteredKernels('webgl', 'test-disposal'); tf.setBackend('test-disposal'); // Compile and run a program. tf.zeros([1000]).sqrt().dataSync(); // Dispose the 2nd backend. tf.backend().dispose(); // Make sure the cache is empty. const cache = getBinaryCache(tf.ENV.getNumber('WEBGL_VERSION')); expect(Object.keys(cache).length).toBe(0); tf.removeBackend('test-disposal'); }); }); describeWithFlags('Custom window size', WEBGL_ENVS, () => { const customBackendName = 'custom-webgl'; beforeAll(() => { const kernelFunc = tf.getKernel('Square', 'webgl').kernelFunc; tf.registerKernel({ kernelName: 'Square', backendName: customBackendName, kernelFunc }); }); afterAll(() => { tf.unregisterKernel('Square', customBackendName); }); xit('Set screen area to be 1x1', () => { // This will set the screen size to 1x1 to make sure the page limit is // very small. spyOnProperty(window, 'screen', 'get') .and.returnValue({ height: 1, width: 1 }); tf.registerBackend(customBackendName, () => new MathBackendWebGL()); tf.setBackend(customBackendName); // Allocate ~40KB. const a = tf.ones([100, 100]); // No gpu memory used yet because of delayed storage. expect(tf.memory().numBytesInGPU).toBe(0); // Expect console.warn() to be called. let numWarnCalls = 0; spyOn(console, 'warn').and.callFake(() => { numWarnCalls++; }); a.square(); expect(numWarnCalls).toBe(1); expect(tf.memory().numBytesInGPU) .toBe(100 * 100 * 4 * 2); // Allocate another 40KB. a.square(); // Expect console.warn() to NOT be called more than once. expect(numWarnCalls).toBe(1); expect(tf.memory().numBytesInGPU) .toBe(100 * 100 * 4 * 3); tf.removeBackend(customBackendName); }); }); const SIZE_UPLOAD_UNIFORM = 4; // Run only for environments that have 32bit floating point support. const FLOAT32_WEBGL_ENVS = { flags: { 'WEBGL_RENDER_FLOAT32_ENABLED': true }, predicate: WEBGL_ENVS.predicate }; describeWithFlags('upload tensors as uniforms', FLOAT32_WEBGL_ENVS, () => { let savedUploadUniformValue; beforeAll(() => { savedUploadUniformValue = tf.env().get('WEBGL_SIZE_UPLOAD_UNIFORM'); tf.env().set('WEBGL_SIZE_UPLOAD_UNIFORM', SIZE_UPLOAD_UNIFORM); }); afterAll(() => { tf.env().set('WEBGL_SIZE_UPLOAD_UNIFORM', savedUploadUniformValue); }); it('small tensor gets uploaded as scalar', () => { let m = tf.memory(); expect(m.numBytesInGPU).toBe(0); const a = tf.zeros([SIZE_UPLOAD_UNIFORM - 1]); a.square(); // Only the result lives on the gpu, the input is gone. m = tf.memory(); expect(m.numBytesInGPU).toBe(a.size * 4); }); it('large tensor gets uploaded to gpu', () => { let m = tf.memory(); expect(m.numBytesInGPU).toBe(0); const a = tf.zeros([SIZE_UPLOAD_UNIFORM + 1]); a.square(); // Both the result and the input live on the gpu. m = tf.memory(); expect(m.numBytesInGPU).toBe(a.size * 4 * 2); }); it('download and re-upload an output of a shader', async () => { const vals = new Float32Array(SIZE_UPLOAD_UNIFORM + 1); vals.fill(2); const a = tf.square(vals); a.dataSync(); // Download to CPU. const res = a.square(); // Re-upload to GPU. const expected = new Float32Array(SIZE_UPLOAD_UNIFORM + 1); expected.fill(16); expectArraysClose(await res.data(), expected); }); }); describeWithFlags('indexing for large tensors', FLOAT32_WEBGL_ENVS, () => { it('properly indexes large tensors', async () => { const range = 3000 * 3000; const aData = new Float32Array(range); for (let i = 0; i < range; i++) { aData[i] = i / range; } const a = tf.tensor1d(aData); const aRelu = a.relu(); expectArraysClose(await a.data(), aData); expectArraysClose(await aRelu.data(), aData); }); }); describeWithFlags('debug on webgl', WEBGL_ENVS, () => { beforeAll(() => { // Silences debug warnings. spyOn(console, 'warn'); tf.enableDebugMode(); }); it('debug mode errors when overflow in tensor construction', () => { const savedRenderFloat32Flag = tf.env().getBool('WEBGL_RENDER_FLOAT32_ENABLED'); tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', false); const a = () => tf.tensor1d([2, Math.pow(2, 17)], 'float32'); expect(a).toThrowError(); tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', savedRenderFloat32Flag); }); it('debug mode errors when underflow in tensor construction', () => { const savedRenderFloat32Flag = tf.env().getBool('WEBGL_RENDER_FLOAT32_ENABLED'); tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', false); const a = () => tf.tensor1d([2, 1e-8], 'float32'); expect(a).toThrowError(); tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', savedRenderFloat32Flag); }); }); const WEBGL1_ENVS = { flags: { 'WEBGL_VERSION': 1 }, predicate: WEBGL_ENVS.predicate }; const WEBGL2_ENVS = { flags: { 'WEBGL_VERSION': 2 }, predicate: WEBGL_ENVS.predicate }; describeWithFlags('computeBytes counts bytes correctly', WEBGL1_ENVS, () => { it('for all physical texture types', () => { const gpgpu = new GPGPUContext(); const shapeRC = [2, 3]; let bytesForTex = computeBytes(shapeRC, PhysicalTextureType.UNPACKED_FLOAT16, gpgpu.gl, gpgpu.textureConfig, false /* isPacked */); expect(bytesForTex).toBe(96); bytesForTex = computeBytes(shapeRC, PhysicalTextureType.UNPACKED_FLOAT32, gpgpu.gl, gpgpu.textureConfig, false /* isPacked */); expect(bytesForTex).toBe(96); bytesForTex = computeBytes(shapeRC, PhysicalTextureType.PACKED_4X1_UNSIGNED_BYTE, gpgpu.gl, gpgpu.textureConfig, true /* isPacked */); expect(bytesForTex).toBe(32); bytesForTex = computeBytes(shapeRC, PhysicalTextureType.PACKED_2X2_FLOAT32, gpgpu.gl, gpgpu.textureConfig, true /* isPacked */); expect(bytesForTex).toBe(32); bytesForTex = computeBytes(shapeRC, PhysicalTextureType.PACKED_2X2_FLOAT16, gpgpu.gl, gpgpu.textureConfig, true /* isPacked */); expect(bytesForTex).toBe(32); gpgpu.dispose(); }); }); describeWithFlags('computeBytes counts bytes correctly', WEBGL2_ENVS, () => { it('test every physical tex type input to computeBytes', () => { const gpgpu = new GPGPUContext(); const shapeRC = [2, 3]; let bytesForTex = computeBytes(shapeRC, PhysicalTextureType.UNPACKED_FLOAT16, gpgpu.gl, gpgpu.textureConfig, false /* isPacked */); expect(bytesForTex).toBe(12); bytesForTex = computeBytes(shapeRC, PhysicalTextureType.UNPACKED_FLOAT32, gpgpu.gl, gpgpu.textureConfig, false /* isPacked */); expect(bytesForTex).toBe(24); bytesForTex = computeBytes(shapeRC, PhysicalTextureType.PACKED_4X1_UNSIGNED_BYTE, gpgpu.gl, gpgpu.textureConfig, true /* isPacked */); expect(bytesForTex).toBe(32); bytesForTex = computeBytes(shapeRC, PhysicalTextureType.PACKED_2X2_FLOAT32, gpgpu.gl, gpgpu.textureConfig, true /* isPacked */); expect(bytesForTex).toBe(32); bytesForTex = computeBytes(shapeRC, PhysicalTextureType.PACKED_2X2_FLOAT16, gpgpu.gl, gpgpu.textureConfig, true /* isPacked */); expect(bytesForTex).toBe(16); gpgpu.dispose(); }); }); describeWithFlags('aggressive texture deletion', WEBGL_ENVS, () => { it('basic', () => { const savedDeleteThreshold = tf.env().get('WEBGL_DELETE_TEXTURE_THRESHOLD'); tf.env().set('WEBGL_DELETE_TEXTURE_THRESHOLD', 0); const a = tf.tensor2d([1, 2, 3, 4, 5, 6], [2, 3]); const b = tf.tensor2d([0, 1, -3, 2, 2, 1], [3, 2]); tf.matMul(a, b); const startNumBytesAllocated = tf.memory().numBytesInGPUAllocated; a.dispose(); b.dispose(); expect(startNumBytesAllocated - tf.memory().numBytesInGPUAllocated) .toBeGreaterThan(0); tf.env().set('WEBGL_DELETE_TEXTURE_THRESHOLD', savedDeleteThreshold); }); }); describeWithFlags('memory webgl', WEBGL_ENVS, () => { it('unreliable is falsy/not present when all tensors are numeric', () => { tf.tensor(1); const mem = tf.memory(); expect(mem.numTensors).toBe(1); expect(mem.numDataBuffers).toBe(1); expect(mem.numBytes).toBe(4); expect(mem.unreliable).toBeFalsy(); }); }); // We do not yet fully support half float backends. These tests are a starting // point. describeWithFlags('backend without render float32 support', WEBGL_ENVS, () => { const savedRenderFloat32Flag = tf.env().getBool('WEBGL_RENDER_FLOAT32_ENABLED'); const customWebGLBackendName = 'half-float-webgl'; beforeAll(() => { tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', false); }); beforeEach(() => { tf.copyRegisteredKernels('webgl', customWebGLBackendName); tf.registerBackend(customWebGLBackendName, () => new MathBackendWebGL(null)); }); afterEach(() => { tf.removeBackend(customWebGLBackendName); }); afterAll(() => { tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', savedRenderFloat32Flag); }); it('basic usage', async () => { tf.setBackend(customWebGLBackendName); const a = tf.tensor2d([1, 2], [1, 2]); const b = tf.tensor2d([1, 2], [1, 2]); const c = tf.add(a, b); expectArraysClose(await c.data(), [2, 4]); }); it('disposing tensors should not cause errors', () => { tf.setBackend(customWebGLBackendName); expect(() => tf.tidy(() => { const a = tf.tensor2d([1, 2], [1, 2]); const b = tf.tensor2d([1, 2], [1, 2]); const c = tf.add(a, b); c.dataSync(); return c.add(tf.tensor2d([2, 4], [1, 2])); })).not.toThrowError(); }); }); describeWithFlags('time webgl', WEBGL_ENVS, () => { it('upload + compute', async () => { const a = tf.zeros([10, 10]); const time = await tf.time(() => a.square()); expect(time.uploadWaitMs > 0); expect(time.downloadWaitMs === 0); expect(time.kernelMs > 0); expect(time.wallMs >= time.kernelMs); }); it('upload + compute + dataSync', async () => { const a = tf.zeros([10, 10]); const time = await tf.time(() => a.square().dataSync()); expect(time.uploadWaitMs > 0); expect(time.downloadWaitMs > 0); expect(time.kernelMs > 0); expect(time.wallMs >= time.kernelMs); }); it('upload + compute + data', async () => { const a = tf.zeros([10, 10]); const time = await tf.time(async () => a.square().data()); expect(time.uploadWaitMs > 0); expect(time.downloadWaitMs > 0); expect(time.kernelMs > 0); expect(time.wallMs >= time.kernelMs); }); it('preupload (not included) + compute + data', async () => { const a = tf.zeros([10, 10]); // Pre-upload a on gpu. a.square(); const time = await tf.time(() => a.sqrt()); // The tensor was already on gpu. expect(time.uploadWaitMs === 0); expect(time.downloadWaitMs === 0); expect(time.kernelMs > 0); expect(time.wallMs >= time.kernelMs); }); it('returns error for kernelMs if query timer extension is unavailable', async () => { const savedQueryReliableValue = tf.env().get('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE'); tf.env().set('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE', false); const a = tf.zeros([10, 10]); const time = await tf.backend().time(() => a.sqrt()); expect(time.kernelMs).toEqual({ error: 'WebGL query timers are not supported in this environment.' }); tf.env().set('WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE', savedQueryReliableValue); }); }); describeWithFlags('caching on cpu', WEBGL_ENVS, () => { const customBackendName = 'cache-on-cpu'; beforeAll(() => { tf.env().set('WEBGL_CPU_FORWARD', false); const kernelFunc = tf.getKernel('Square', 'webgl').kernelFunc; tf.registerKernel({ kernelName: 'Square', backendName: customBackendName, kernelFunc }); }); afterAll(() => { tf.unregisterKernel('Square', customBackendName); }); it('caches on cpu after async read', async () => { const backend = new MathBackendWebGL(); tf.registerBackend(customBackendName, () => backend); tf.setBackend(customBackendName); const t = tf.square(2); const info = backend.getDataInfo(t.dataId); // Make sure the tensor is on the GPU. expect(info.values == null).toBe(true); await t.data(); // Make sure the tensor is cached on CPU. expect(info.values).not.toBe(null); tf.removeBackend(customBackendName); }); it('caches on cpu after sync read', () => { const backend = new MathBackendWebGL(); tf.registerBackend(customBackendName, () => backend); tf.setBackend(customBackendName); const t = tf.square(2); const info = backend.getDataInfo(t.dataId); // Make sure the tensor is on the GPU. expect(info.values == null).toBe(true); t.dataSync(); // Make sure the tensor is cached on CPU. expect(info.values).not.toBe(null); tf.removeBackend(customBackendName); }); }); describeWithFlags('WebGL backend has sync init', WEBGL_ENVS, () => { it('can do matmul without waiting for ready', async () => { const customWebGLBackendName = 'my-webgl'; tf.copyRegisteredKernels('webgl', customWebGLBackendName); tf.registerBackend(customWebGLBackendName, () => { return new MathBackendWebGL(); }); tf.setBackend(customWebGLBackendName); const a = tf.tensor1d([5]); const b = tf.tensor1d([3]); const res = tf.dot(a, b); expectArraysClose(await res.data(), 15); tf.dispose([a, b, res]); tf.removeBackend(customWebGLBackendName); }); }); //# sourceMappingURL=backend_webgl_test.js.map
0
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests/test/Mean_test.js
/** * @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ import * as tf from '@tensorflow/tfjs-core'; import { test_util } from '@tensorflow/tfjs-core'; const { expectArraysClose } = test_util; // tslint:disable-next-line: no-imports-from-dist import { ALL_ENVS, describeWithFlags } from '@tensorflow/tfjs-core/dist/jasmine_util'; describeWithFlags('Mean.', ALL_ENVS, () => { it('does not have memory leak and works for large dimensions.', async () => { const beforeDataIds = tf.engine().backend.numDataIds(); const a = tf.ones([1, 70000]); const r = tf.mean(a); expect(r.dtype).toBe('float32'); expectArraysClose(await r.data(), 1); const afterResDataIds = tf.engine().backend.numDataIds(); expect(afterResDataIds).toEqual(beforeDataIds + 2); a.dispose(); r.dispose(); const afterDisposeDataIds = tf.engine().backend.numDataIds(); expect(afterDisposeDataIds).toEqual(beforeDataIds); }); }); //# sourceMappingURL=Mean_test.js.map
0
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests/test/webgl_util_test.js
/** * @license * Copyright 2017 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ import * as tf from '@tensorflow/tfjs-core'; import { util } from '@tensorflow/tfjs-core'; // tslint:disable-next-line: no-imports-from-dist import { describeWithFlags } from '@tensorflow/tfjs-core/dist/jasmine_util'; import { WEBGL_ENVS } from '@tensorflow/tfjs-backend-webgl/dist/backend_webgl_test_registry'; import * as webgl_util from '@tensorflow/tfjs-backend-webgl/dist/webgl_util'; describeWithFlags('getTextureShapeFromLogicalShape', WEBGL_ENVS, () => { it('scalar', () => { const texShape = webgl_util.getTextureShapeFromLogicalShape([]); expect(texShape).toEqual([1, 1]); }); it('1d', () => { const texShape = webgl_util.getTextureShapeFromLogicalShape([4]); expect(texShape).toEqual([1, 4]); }); it('2d stays same', () => { let texShape = webgl_util.getTextureShapeFromLogicalShape([5, 2]); expect(texShape).toEqual([5, 2]); texShape = webgl_util.getTextureShapeFromLogicalShape([5, 1]); expect(texShape).toEqual([5, 1]); texShape = webgl_util.getTextureShapeFromLogicalShape([1, 5]); expect(texShape).toEqual([1, 5]); }); it('3d 2x3x4', () => { const texShape = webgl_util.getTextureShapeFromLogicalShape([2, 3, 4]); expect(texShape).toEqual([6, 4]); }); it('3d 3x256x256', () => { const texShape = webgl_util.getTextureShapeFromLogicalShape([3, 256, 256]); expect(texShape).toEqual([3 * 256, 256]); }); it('3d 2x1x4 got squeezed', () => { const texShape = webgl_util.getTextureShapeFromLogicalShape([2, 1, 4]); expect(texShape).toEqual([2, 4]); }); it('3d 1x8x2 got squeezed', () => { const texShape = webgl_util.getTextureShapeFromLogicalShape([1, 8, 2]); expect(texShape).toEqual([8, 2]); }); it('4d 2x2x256x256 got squeezed', () => { const texShape = webgl_util.getTextureShapeFromLogicalShape([2, 2, 256, 256]); expect(texShape).toEqual([2 * 2 * 256, 256]); }); it('4d 1x8x1x3 got squeezed', () => { const texShape = webgl_util.getTextureShapeFromLogicalShape([1, 8, 1, 3]); expect(texShape).toEqual([8, 3]); }); it('4d 1x3x1x8 got squeezed', () => { const texShape = webgl_util.getTextureShapeFromLogicalShape([1, 3, 1, 8]); expect(texShape).toEqual([3, 8]); }); }); describeWithFlags('getTextureShapeFromLogicalShape packed', WEBGL_ENVS, () => { it('textures less than 2x max size of platform preserve their shapes', () => { const isPacked = true; const logicalShape = [ 2, util.nearestLargerEven(tf.env().getNumber('WEBGL_MAX_TEXTURE_SIZE') + 1) ]; const texShape = webgl_util.getTextureShapeFromLogicalShape(logicalShape, isPacked); expect(texShape).toEqual(logicalShape); }); it('rows/columns do not get squeezed', () => { const isPacked = true; const logicalShape = [1, 1, 1]; const texShape = webgl_util.getTextureShapeFromLogicalShape(logicalShape, isPacked); expect(texShape).toEqual([2, 2]); }); it('squarified texture shapes account for packing constraints', () => { const isPacked = true; const max = tf.env().getNumber('WEBGL_MAX_TEXTURE_SIZE'); tf.env().set('WEBGL_MAX_TEXTURE_SIZE', 5); const logicalShape = [1, 12]; const texShape = webgl_util.getTextureShapeFromLogicalShape(logicalShape, isPacked); tf.env().set('WEBGL_MAX_TEXTURE_SIZE', max); expect(texShape).toEqual([6, 4]); }); }); describeWithFlags('isReshapeFree', WEBGL_ENVS, () => { it('is free when shapes have the same inner dimensions', () => { const before = [1, 2, 3]; const after = [5, 2, 3]; expect(webgl_util.isReshapeFree(before, after)).toBe(true); }); it('is free when one of the shapes is a scalar', () => { const before = []; const after = [1, 2, 3]; expect(webgl_util.isReshapeFree(before, after)).toBe(true); }); it('is free when one of the dimensions equals 0', () => { const before = [1, 0]; const after = [1, 2, 3]; expect(webgl_util.isReshapeFree(before, after)).toBe(true); }); it('is free when one shape is a vector and the final dimensions match', () => { const before = [9]; const after = [1, 1, 9]; expect(webgl_util.isReshapeFree(before, after)).toBe(true); }); it('is free when one shape is a vector and the other has 1 row' + 'in every batch and the final dimensions are even', () => { const before = [10]; const after = [5, 1, 2]; expect(webgl_util.isReshapeFree(before, after)).toBe(true); }); it('is not free when one shape is a vector and the final dimensions' + 'do not match and are not even', () => { const before = [18]; const after = [2, 1, 9]; expect(webgl_util.isReshapeFree(before, after)).toBe(false); }); it('is free if the rows are divisible by two and the columns are the same', () => { const before = [1, 2, 3]; const after = [1, 4, 3]; expect(webgl_util.isReshapeFree(before, after)).toBe(true); }); it('is not free when the inner dimensions are different and even', () => { const before = [1, 2, 4]; const after = [1, 8, 10]; expect(webgl_util.isReshapeFree(before, after)).toBe(false); }); it('is not free when the inner dimensions are different and not all even', () => { const before = [1, 2, 3]; const after = [1, 3, 2]; expect(webgl_util.isReshapeFree(before, after)).toBe(false); }); }); //# sourceMappingURL=webgl_util_test.js.map
0
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests/test/Mean_test.d.ts
/** * @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ export {};
0
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests/test/Complex_test.js
/** * @license * Copyright 2020 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ import * as tf from '@tensorflow/tfjs-core'; import { test_util } from '@tensorflow/tfjs-core'; const { expectArraysClose } = test_util; // tslint:disable-next-line: no-imports-from-dist import { describeWithFlags, ALL_ENVS } from '@tensorflow/tfjs-core/dist/jasmine_util'; const BYTES_PER_COMPLEX_ELEMENT = 4 * 2; describeWithFlags('complex64 memory', ALL_ENVS, () => { it('usage', async () => { const webglSizeUploadUniformFlagSaved = tf.env().get('WEBGL_SIZE_UPLOAD_UNIFORM'); tf.env().set('WEBGL_SIZE_UPLOAD_UNIFORM', 4); let numTensors = tf.memory().numTensors; let numBytes = tf.memory().numBytes; let numDataIds = tf.engine().backend.numDataIds(); const startTensors = numTensors; const startNumBytes = numBytes; const startNumBytesInGPU = tf.memory().numBytesInGPU; const startDataIds = numDataIds; const real1 = tf.tensor1d([1]); const imag1 = tf.tensor1d([2]); // 2 new Tensors: real1, imag1, and two data buckets created. expect(tf.memory().numTensors).toBe(numTensors + 2); expect(tf.memory().numBytes).toBe(numBytes + BYTES_PER_COMPLEX_ELEMENT); expect(tf.engine().backend.numDataIds()).toBe(numDataIds + 2); numTensors = tf.memory().numTensors; numBytes = tf.memory().numBytes; numDataIds = tf.engine().backend.numDataIds(); const complex1 = tf.complex(real1, imag1); // 1 new complex Tensor and 1 new data bucket created. No new bytes // allocated. expect(tf.memory().numTensors).toBe(numTensors + 1); expect(tf.memory().numBytes).toBe(numBytes); expect(tf.engine().backend.numDataIds()).toBe(numDataIds + 1); numTensors = tf.memory().numTensors; numBytes = tf.memory().numBytes; numDataIds = tf.engine().backend.numDataIds(); const real2 = tf.tensor1d([3]); const imag2 = tf.tensor1d([4]); // 2 new Tensors: real2, imag2, and 2 new data buckets. expect(tf.memory().numTensors).toBe(numTensors + 2); expect(tf.memory().numBytes).toBe(numBytes + BYTES_PER_COMPLEX_ELEMENT); expect(tf.engine().backend.numDataIds()).toBe(numDataIds + 2); numTensors = tf.memory().numTensors; numBytes = tf.memory().numBytes; numDataIds = tf.engine().backend.numDataIds(); const complex2 = tf.complex(real2, imag2); // 1 new Tensor and 1 new data bucket. expect(tf.memory().numTensors).toBe(numTensors + 1); // numBytes stays the same because it is determined by tensor creation at // the engine level, and we do not increment memory for complex tensors // (complex tensors track their own memory). expect(tf.memory().numBytes).toBe(numBytes); expect(tf.engine().backend.numDataIds()).toBe(numDataIds + 1); numTensors = tf.memory().numTensors; numBytes = tf.memory().numBytes; numDataIds = tf.engine().backend.numDataIds(); const result = complex1.add(complex2); // A complex tensor is created, which is composed of real and imag parts. // They should not increase tensor count, only complex tensor does. // 3 new data buckets created for complex, real and imag. expect(tf.memory().numTensors).toBe(numTensors + 1); expect(tf.memory().numBytes).toBe(numBytes); expect(tf.engine().backend.numDataIds()).toBe(numDataIds + 3); // Two new 1x1 textures are created to compute the sum of real / imag // components, respectively. No new textures are allocated for the inputs // because they are beneath the uniform upload threshold. expect(tf.memory().numBytesInGPU) .toBe(startNumBytesInGPU + BYTES_PER_COMPLEX_ELEMENT); numTensors = tf.memory().numTensors; numDataIds = tf.engine().backend.numDataIds(); expect(result.dtype).toBe('complex64'); expect(result.shape).toEqual([1]); expectArraysClose(await result.data(), [4, 6]); const real = tf.real(result); // A new tensor is created. No new data buckets created. expect(tf.memory().numTensors).toBe(numTensors + 1); expect(tf.memory().numBytes).toBe(numBytes + 4); expect(tf.engine().backend.numDataIds()).toBe(numDataIds); numTensors = tf.memory().numTensors; numBytes = tf.memory().numBytes; numDataIds = tf.engine().backend.numDataIds(); expectArraysClose(await real.data(), [4]); const imag = tf.imag(result); // A new tensor is created. No new data buckets created. expect(tf.memory().numTensors).toBe(numTensors + 1); expect(tf.memory().numBytes).toBe(numBytes + 4); expect(tf.engine().backend.numDataIds()).toBe(numDataIds); expectArraysClose(await imag.data(), [6]); // After disposing, there should be no tensors. real1.dispose(); imag1.dispose(); real2.dispose(); imag2.dispose(); complex1.dispose(); complex2.dispose(); result.dispose(); real.dispose(); imag.dispose(); expect(tf.memory().numTensors).toBe(startTensors); expect(tf.memory().numBytes).toBe(startNumBytes); expect(tf.engine().backend.numDataIds()).toBe(startDataIds); expect(tf.memory().numBytesInGPU) .toBe(startNumBytesInGPU); tf.env().set('WEBGL_SIZE_UPLOAD_UNIFORM', webglSizeUploadUniformFlagSaved); }); it('Creating tf.real, tf.imag from complex.', async () => { let numTensors = tf.memory().numTensors; let numDataIds = tf.engine().backend.numDataIds(); const startTensors = numTensors; const startDataIds = numDataIds; const complex = tf.complex([3, 30], [4, 40]); // 1 new tensor, 3 new data buckets. expect(tf.memory().numTensors).toBe(numTensors + 1); expect(tf.engine().backend.numDataIds()).toBe(numDataIds + 3); numTensors = tf.memory().numTensors; numDataIds = tf.engine().backend.numDataIds(); const real = tf.real(complex); const imag = tf.imag(complex); // 2 new tensors, no new data buckets. expect(tf.memory().numTensors).toBe(numTensors + 2); expect(tf.engine().backend.numDataIds()).toBe(numDataIds); numTensors = tf.memory().numTensors; numDataIds = tf.engine().backend.numDataIds(); complex.dispose(); // 1 fewer tensor, 1 fewer data buckets. expect(tf.memory().numTensors).toBe(numTensors - 1); expect(tf.engine().backend.numDataIds()).toBe(numDataIds - 1); expectArraysClose(await real.data(), [3, 30]); expectArraysClose(await imag.data(), [4, 40]); numTensors = tf.memory().numTensors; numDataIds = tf.engine().backend.numDataIds(); real.dispose(); imag.dispose(); // Zero net tensors / data buckets. expect(tf.memory().numTensors).toBe(startTensors); expect(tf.engine().backend.numDataIds()).toBe(startDataIds); }); it('tf.complex disposing underlying tensors', async () => { const numTensors = tf.memory().numTensors; const numDataIds = tf.engine().backend.numDataIds(); const real = tf.tensor1d([3, 30]); const imag = tf.tensor1d([4, 40]); expect(tf.memory().numTensors).toEqual(numTensors + 2); expect(tf.engine().backend.numDataIds()).toEqual(numDataIds + 2); const complex = tf.complex(real, imag); // 1 new tensor is created for complex. real and imag data buckets created. expect(tf.memory().numTensors).toEqual(numTensors + 3); expect(tf.engine().backend.numDataIds()).toEqual(numDataIds + 3); real.dispose(); imag.dispose(); expect(tf.memory().numTensors).toEqual(numTensors + 1); expect(tf.engine().backend.numDataIds()).toEqual(numDataIds + 3); expect(complex.dtype).toBe('complex64'); expect(complex.shape).toEqual(real.shape); expectArraysClose(await complex.data(), [3, 4, 30, 40]); complex.dispose(); expect(tf.memory().numTensors).toEqual(numTensors); expect(tf.engine().backend.numDataIds()).toEqual(numDataIds); }); it('reshape', async () => { const memoryBefore = tf.memory(); const numDataIdsBefore = tf.engine().backend.numDataIds(); let numTensors = memoryBefore.numTensors; let numDataIds = numDataIdsBefore; const a = tf.complex([[1, 3, 5], [7, 9, 11]], [[2, 4, 6], [8, 10, 12]]); // 1 new tensor, the complex64 tensor expect(tf.memory().numTensors).toBe(memoryBefore.numTensors + 1); // 1 new tensor and 2 underlying data buckets for real and imag. expect(tf.engine().backend.numDataIds()).toBe(numDataIdsBefore + 3); numTensors = tf.memory().numTensors; numDataIds = tf.engine().backend.numDataIds(); const b = a.reshape([6]); // 1 new tensor from the reshape. expect(tf.memory().numTensors).toBe(numTensors + 1); // No new data buckets. expect(tf.engine().backend.numDataIds()).toBe(numDataIds); expect(b.dtype).toBe('complex64'); expect(b.shape).toEqual([6]); expectArraysClose(await a.data(), await b.data()); b.dispose(); // 1 complex tensor should be disposed. expect(tf.memory().numTensors).toBe(numTensors); // Data buckets not deleted yet. expect(tf.engine().backend.numDataIds()).toBe(numDataIds); a.dispose(); // All the tensors should now be disposed. expect(tf.memory().numTensors).toBe(memoryBefore.numTensors); // The underlying memory should now be released. expect(tf.engine().backend.numDataIds()).toBe(numDataIdsBefore); }); it('clone', async () => { const memoryBefore = tf.memory(); const numDataIdsBefore = tf.engine().backend.numDataIds(); const a = tf.complex([[1, 3, 5], [7, 9, 11]], [[2, 4, 6], [8, 10, 12]]); // 1 new tensor, the complex64 tensor expect(tf.memory().numTensors).toBe(memoryBefore.numTensors + 1); // 1 new tensor and 2 underlying data buckets for real and imag. expect(tf.engine().backend.numDataIds()).toBe(numDataIdsBefore + 3); const b = a.clone(); // 1 new tensor from the clone. expect(tf.memory().numTensors).toBe(memoryBefore.numTensors + 2); // No new data buckets. expect(tf.engine().backend.numDataIds()).toBe(numDataIdsBefore + 3); expect(b.dtype).toBe('complex64'); expectArraysClose(await a.data(), await b.data()); b.dispose(); // 1 complex tensor should be disposed. expect(tf.memory().numTensors).toBe(memoryBefore.numTensors + 1); // Data bucket not deleted yet. expect(tf.engine().backend.numDataIds()).toBe(numDataIdsBefore + 3); a.dispose(); // All the tensors should now be disposed. expect(tf.memory().numTensors).toBe(memoryBefore.numTensors); expect(tf.engine().backend.numDataIds()).toBe(numDataIdsBefore); }); it('Multiple complex tensors sharing same underlying components works', async () => { const numTensors = tf.memory().numTensors; const numDataIds = tf.engine().backend.numDataIds(); const real = tf.tensor1d([1]); const imag = tf.tensor1d([2]); expect(tf.memory().numTensors).toEqual(numTensors + 2); expect(tf.engine().backend.numDataIds()).toEqual(numDataIds + 2); const complex1 = tf.complex(real, imag); const complex2 = tf.complex(real, imag); expect(tf.memory().numTensors).toEqual(numTensors + 4); expect(tf.engine().backend.numDataIds()).toEqual(numDataIds + 4); real.dispose(); expect(tf.memory().numTensors).toEqual(numTensors + 3); expect(tf.engine().backend.numDataIds()).toEqual(numDataIds + 4); complex1.dispose(); expect(tf.memory().numTensors).toEqual(numTensors + 2); expect(tf.engine().backend.numDataIds()).toEqual(numDataIds + 3); expectArraysClose(await complex2.data(), [1, 2]); }); it('tidy should not have mem leak', async () => { const numTensors = tf.memory().numTensors; const numDataIds = tf.engine().backend.numDataIds(); const complex = tf.tidy(() => { const real = tf.tensor1d([3, 30]); const realReshape = tf.reshape(real, [2]); const imag = tf.tensor1d([4, 40]); const imagReshape = tf.reshape(imag, [2]); expect(tf.memory().numTensors).toEqual(numTensors + 4); expect(tf.engine().backend.numDataIds()).toEqual(numDataIds + 2); const complex = tf.complex(realReshape, imagReshape); // 1 new tensor is created for complex. real and imag data buckets // created. expect(tf.memory().numTensors).toEqual(numTensors + 5); expect(tf.engine().backend.numDataIds()).toEqual(numDataIds + 3); return complex; }); complex.dispose(); expect(tf.memory().numTensors).toEqual(numTensors); expect(tf.engine().backend.numDataIds()).toEqual(numDataIds); }); }); //# sourceMappingURL=Complex_test.js.map
0
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests/test/gpgpu_util_test.js
/** * @license * Copyright 2017 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ // tslint:disable-next-line: no-imports-from-dist import { describeWithFlags } from '@tensorflow/tfjs-core/dist/jasmine_util'; import { WEBGL_ENVS } from '@tensorflow/tfjs-backend-webgl/dist/backend_webgl_test_registry'; import { GPGPUContext } from '@tensorflow/tfjs-backend-webgl/dist/gpgpu_context'; import * as gpgpu_util from '@tensorflow/tfjs-backend-webgl/dist/gpgpu_util'; import * as tex_util from '@tensorflow/tfjs-backend-webgl/dist/tex_util'; describeWithFlags('gpgpu_util createWebGLContext', WEBGL_ENVS, () => { let gpgpu; beforeEach(() => { gpgpu = new GPGPUContext(); }); afterEach(() => { gpgpu.dispose(); }); it('disables DEPTH_TEST and STENCIL_TEST', () => { expect(gpgpu.gl.getParameter(gpgpu.gl.DEPTH_TEST)).toEqual(false); expect(gpgpu.gl.getParameter(gpgpu.gl.STENCIL_TEST)).toEqual(false); }); it('disables BLEND', () => { expect(gpgpu.gl.getParameter(gpgpu.gl.BLEND)).toEqual(false); }); it('disables DITHER, POLYGON_OFFSET_FILL', () => { expect(gpgpu.gl.getParameter(gpgpu.gl.DITHER)).toEqual(false); expect(gpgpu.gl.getParameter(gpgpu.gl.POLYGON_OFFSET_FILL)).toEqual(false); }); it('enables CULL_FACE with BACK', () => { expect(gpgpu.gl.getParameter(gpgpu.gl.CULL_FACE)).toEqual(true); expect(gpgpu.gl.getParameter(gpgpu.gl.CULL_FACE_MODE)) .toEqual(gpgpu.gl.BACK); }); it('enables SCISSOR_TEST', () => { expect(gpgpu.gl.getParameter(gpgpu.gl.SCISSOR_TEST)).toEqual(true); }); }); describeWithFlags('gpgpu_util createFloat32MatrixTexture', WEBGL_ENVS, () => { it('sets the TEXTURE_WRAP S+T parameters to CLAMP_TO_EDGE', () => { const gpgpu = new GPGPUContext(); const textureConfig = tex_util.getTextureConfig(gpgpu.gl); const tex = gpgpu_util.createFloat32MatrixTexture(gpgpu.gl, 32, 32, textureConfig); gpgpu.gl.bindTexture(gpgpu.gl.TEXTURE_2D, tex); expect(gpgpu.gl.getTexParameter(gpgpu.gl.TEXTURE_2D, gpgpu.gl.TEXTURE_WRAP_S)) .toEqual(gpgpu.gl.CLAMP_TO_EDGE); expect(gpgpu.gl.getTexParameter(gpgpu.gl.TEXTURE_2D, gpgpu.gl.TEXTURE_WRAP_T)) .toEqual(gpgpu.gl.CLAMP_TO_EDGE); gpgpu.gl.bindTexture(gpgpu.gl.TEXTURE_2D, null); gpgpu.deleteMatrixTexture(tex); gpgpu.dispose(); }); it('sets the TEXTURE_[MIN|MAG]_FILTER parameters to NEAREST', () => { const gpgpu = new GPGPUContext(); const textureConfig = tex_util.getTextureConfig(gpgpu.gl); const tex = gpgpu_util.createFloat32MatrixTexture(gpgpu.gl, 32, 32, textureConfig); gpgpu.gl.bindTexture(gpgpu.gl.TEXTURE_2D, tex); expect(gpgpu.gl.getTexParameter(gpgpu.gl.TEXTURE_2D, gpgpu.gl.TEXTURE_MIN_FILTER)) .toEqual(gpgpu.gl.NEAREST); expect(gpgpu.gl.getTexParameter(gpgpu.gl.TEXTURE_2D, gpgpu.gl.TEXTURE_MAG_FILTER)) .toEqual(gpgpu.gl.NEAREST); gpgpu.gl.bindTexture(gpgpu.gl.TEXTURE_2D, null); gpgpu.deleteMatrixTexture(tex); gpgpu.dispose(); }); }); describeWithFlags('gpgpu_util createPackedMatrixTexture', WEBGL_ENVS, () => { it('sets the TEXTURE_WRAP S+T parameters to CLAMP_TO_EDGE', () => { const gpgpu = new GPGPUContext(); const textureConfig = tex_util.getTextureConfig(gpgpu.gl); const tex = gpgpu_util.createPackedMatrixTexture(gpgpu.gl, 32, 32, textureConfig); gpgpu.gl.bindTexture(gpgpu.gl.TEXTURE_2D, tex); expect(gpgpu.gl.getTexParameter(gpgpu.gl.TEXTURE_2D, gpgpu.gl.TEXTURE_WRAP_S)) .toEqual(gpgpu.gl.CLAMP_TO_EDGE); expect(gpgpu.gl.getTexParameter(gpgpu.gl.TEXTURE_2D, gpgpu.gl.TEXTURE_WRAP_T)) .toEqual(gpgpu.gl.CLAMP_TO_EDGE); gpgpu.gl.bindTexture(gpgpu.gl.TEXTURE_2D, null); gpgpu.deleteMatrixTexture(tex); gpgpu.dispose(); }); it('sets the TEXTURE_[MIN|MAG]_FILTER parameters to NEAREST', () => { const gpgpu = new GPGPUContext(); const textureConfig = tex_util.getTextureConfig(gpgpu.gl); const tex = gpgpu_util.createPackedMatrixTexture(gpgpu.gl, 32, 32, textureConfig); gpgpu.gl.bindTexture(gpgpu.gl.TEXTURE_2D, tex); expect(gpgpu.gl.getTexParameter(gpgpu.gl.TEXTURE_2D, gpgpu.gl.TEXTURE_MIN_FILTER)) .toEqual(gpgpu.gl.NEAREST); expect(gpgpu.gl.getTexParameter(gpgpu.gl.TEXTURE_2D, gpgpu.gl.TEXTURE_MAG_FILTER)) .toEqual(gpgpu.gl.NEAREST); gpgpu.gl.bindTexture(gpgpu.gl.TEXTURE_2D, null); gpgpu.deleteMatrixTexture(tex); gpgpu.dispose(); }); }); //# sourceMappingURL=gpgpu_util_test.js.map
0
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests
rapidsai_public_repos/node/modules/demo/tfjs/webgl-tests/test/tex_util_test.js
/** * @license * Copyright 2017 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ // tslint:disable-next-line: no-imports-from-dist import { test_util } from '@tensorflow/tfjs-core'; // tslint:disable-next-line: no-imports-from-dist import { describeWithFlags } from '@tensorflow/tfjs-core/dist/jasmine_util'; const { expectArraysClose } = test_util; import { WEBGL_ENVS } from '@tensorflow/tfjs-backend-webgl/dist/backend_webgl_test_registry'; import * as tex_util from '@tensorflow/tfjs-backend-webgl/dist/tex_util'; describe('tex_util getUnpackedMatrixTextureShapeWidthHeight', () => { it('[1x1] => [1x1]', () => { expect(tex_util.getUnpackedMatrixTextureShapeWidthHeight(1, 1)).toEqual([ 1, 1 ]); }); it('[MxN] => [NxM]', () => { expect(tex_util.getUnpackedMatrixTextureShapeWidthHeight(123, 456)) .toEqual([456, 123]); }); }); describe('tex_util getPackedMatrixTextureShapeWidthHeight', () => { it('[1x1] => [1x1]', () => { const shape = tex_util.getPackedMatrixTextureShapeWidthHeight(1, 1); expect(shape).toEqual([1, 1]); }); it('[1x2] => [1x1]', () => { const shape = tex_util.getPackedMatrixTextureShapeWidthHeight(1, 2); expect(shape).toEqual([1, 1]); }); it('[2x1] => [1x1]', () => { const shape = tex_util.getPackedMatrixTextureShapeWidthHeight(2, 1); expect(shape).toEqual([1, 1]); }); it('[2x2] => [1x1]', () => { const shape = tex_util.getPackedMatrixTextureShapeWidthHeight(2, 2); expect(shape).toEqual([1, 1]); }); it('[3x3] => [2x2]', () => { const shape = tex_util.getPackedMatrixTextureShapeWidthHeight(3, 3); expect(shape).toEqual([2, 2]); }); it('[4x3] => [2x2]', () => { const shape = tex_util.getPackedMatrixTextureShapeWidthHeight(4, 3); expect(shape).toEqual([2, 2]); }); it('[3x4] => [2x2]', () => { const shape = tex_util.getPackedMatrixTextureShapeWidthHeight(3, 4); expect(shape).toEqual([2, 2]); }); it('[4x4] => [2x2]', () => { const shape = tex_util.getPackedMatrixTextureShapeWidthHeight(4, 4); expect(shape).toEqual([2, 2]); }); it('[1024x1024] => [512x512]', () => { const shape = tex_util.getPackedMatrixTextureShapeWidthHeight(1024, 1024); expect(shape).toEqual([512, 512]); }); it('[MxN] => [ceil(N/2)xceil(M/2)]', () => { const M = 123; const N = 5013; const shape = tex_util.getPackedMatrixTextureShapeWidthHeight(M, N); expect(shape).toEqual([Math.ceil(N / 2), Math.ceil(M / 2)]); }); }); describeWithFlags('tex_util getDenseTexShape', WEBGL_ENVS, () => { it('basic', () => { const shape = [1, 3, 3, 4]; const denseShape = tex_util.getDenseTexShape(shape); expectArraysClose(denseShape, [3, 3]); }); }); //# sourceMappingURL=tex_util_test.js.map
0
rapidsai_public_repos/node/modules
rapidsai_public_repos/node/modules/cuda/package.json
{ "name": "@rapidsai/cuda", "version": "22.12.2", "description": "NVIDIA CUDA driver and runtime API bindings", "main": "index.js", "types": "build/js", "license": "Apache-2.0", "author": "NVIDIA, Inc. (https://nvidia.com/)", "maintainers": [ "Paul Taylor <paul.e.taylor@me.com>" ], "homepage": "https://github.com/rapidsai/node/tree/main/modules/core#readme", "bugs": { "url": "https://github.com/rapidsai/node/issues" }, "repository": { "type": "git", "url": "git+https://github.com/rapidsai/node.git" }, "scripts": { "install": "npx rapidsai-install-native-module", "clean": "rimraf build doc compile_commands.json", "doc": "rimraf doc && typedoc --options typedoc.js", "test": "node -r dotenv/config node_modules/.bin/jest -c jest.config.js", "build": "yarn tsc:build && yarn cpp:build", "build:debug": "yarn tsc:build && yarn cpp:build:debug", "compile": "yarn tsc:build && yarn cpp:compile", "compile:debug": "yarn tsc:build && yarn cpp:compile:debug", "rebuild": "yarn tsc:build && yarn cpp:rebuild", "rebuild:debug": "yarn tsc:build && yarn cpp:rebuild:debug", "cpp:clean": "npx cmake-js clean -O build/Release", "cpp:clean:debug": "npx cmake-js clean -O build/Debug", "cpp:build": "npx cmake-js build -g -O build/Release", "cpp:build:debug": "npx cmake-js build -g -D -O build/Debug", "cpp:compile": "npx cmake-js compile -g -O build/Release", "postcpp:compile": "npx rapidsai-merge-compile-commands", "cpp:compile:debug": "npx cmake-js compile -g -D -O build/Debug", "postcpp:compile:debug": "npx rapidsai-merge-compile-commands", "cpp:configure": "npx cmake-js configure -g -O build/Release", "postcpp:configure": "npx rapidsai-merge-compile-commands", "cpp:configure:debug": "npx cmake-js configure -g -D -O build/Debug", "postcpp:configure:debug": "npx rapidsai-merge-compile-commands", "cpp:rebuild": "npx cmake-js rebuild -g -O build/Release", "postcpp:rebuild": "npx rapidsai-merge-compile-commands", "cpp:rebuild:debug": "npx cmake-js rebuild -g -D -O build/Debug", "postcpp:rebuild:debug": "npx rapidsai-merge-compile-commands", "cpp:reconfigure": "npx cmake-js reconfigure -g -O build/Release", "postcpp:reconfigure": "npx rapidsai-merge-compile-commands", "cpp:reconfigure:debug": "npx cmake-js reconfigure -g -D -O build/Debug", "postcpp:reconfigure:debug": "npx rapidsai-merge-compile-commands", "tsc:clean": "rimraf build/js", "tsc:build": "yarn tsc:clean && tsc -p ./tsconfig.json", "tsc:watch": "yarn tsc:clean && tsc -p ./tsconfig.json -w", "dev:cpack:enabled": "echo $npm_package_name" }, "dependencies": { "@rapidsai/core": "~22.12.2" }, "files": [ "LICENSE", "README.md", "index.js", "package.json", "CMakeLists.txt", "src/node_cuda", "src/visit_struct", "build/js" ] }
0
rapidsai_public_repos/node/modules
rapidsai_public_repos/node/modules/cuda/index.js
// Copyright (c) 2020, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. module.exports = require('./build/js/index');
0
rapidsai_public_repos/node/modules
rapidsai_public_repos/node/modules/cuda/jest.config.js
// Copyright (c) 2020-2021, NVIDIA CORPORATION. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. try { require('dotenv').config(); } catch (e) {} module.exports = { 'verbose': true, 'testEnvironment': 'node', 'maxWorkers': process.env.PARALLEL_LEVEL || 1, 'globals': {'ts-jest': {'diagnostics': false, 'tsconfig': 'test/tsconfig.json'}}, 'rootDir': './', 'roots': ['<rootDir>/test/'], 'moduleFileExtensions': ['js', 'ts', 'tsx'], 'coverageReporters': ['lcov'], 'coveragePathIgnorePatterns': ['test\\/.*\\.(ts|tsx|js)$', '/node_modules/'], 'transform': {'^.+\\.jsx?$': 'ts-jest', '^.+\\.tsx?$': 'ts-jest'}, 'transformIgnorePatterns': ['/build/(js|Debug|Release)/*$', '/node_modules/(?!web-stream-tools).+\\.js$'], 'testRegex': '(.*(-|\\.)(test|spec)s?)\\.(ts|tsx|js)$', 'preset': 'ts-jest', 'testMatch': null, 'moduleNameMapper': { '^@rapidsai\/cuda(.*)': '<rootDir>/src/$1', '^\.\.\/(Debug|Release)\/(rapidsai_cuda.node)$': '<rootDir>/build/$1/$2', } };
0