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/ipc/umap/layers
rapidsai_public_repos/node/modules/demo/ipc/umap/layers/node/node-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. // 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. export default `\ #define SHADER_NAME node-layer-fragment-shader precision highp float; uniform bool filled; uniform float stroked; varying vec4 vFillColor; varying vec4 vLineColor; varying vec2 unitPosition; varying float innerUnitRadius; varying float outerRadiusPixels; void main(void) { geometry.uv = unitPosition; float distToCenter = length(unitPosition) * outerRadiusPixels; float inCircle = smoothedge(distToCenter, outerRadiusPixels); if (inCircle == 0.0) { discard; } if (stroked > 0.5) { float isLine = smoothedge(innerUnitRadius * outerRadiusPixels, distToCenter); if (filled) { gl_FragColor = mix(vFillColor, vLineColor, isLine); } else { if (isLine == 0.0) { discard; } gl_FragColor = vec4(vLineColor.rgb, vLineColor.a * isLine); } } else if (filled) { gl_FragColor = vFillColor; } else { discard; } gl_FragColor.a *= inCircle; DECKGL_FILTER_COLOR(gl_FragColor, geometry); } `;
0
rapidsai_public_repos/node/modules/demo/ipc/umap/layers
rapidsai_public_repos/node/modules/demo/ipc/umap/layers/node/node-layer-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. // 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. export default `\ #define SHADER_NAME node-layer-vertex-shader attribute vec3 positions; attribute vec2 instancePositions; attribute vec2 instancePositions64Low; attribute float instanceRadius; attribute float instanceLineWidths; attribute vec4 instanceFillColors; attribute vec4 instanceLineColors; attribute vec3 instancePickingColors; uniform float opacity; uniform float radiusScale; uniform float radiusMinPixels; uniform float radiusMaxPixels; uniform float lineWidthScale; uniform float lineWidthMinPixels; uniform float lineWidthMaxPixels; uniform float stroked; uniform bool filled; varying vec4 vFillColor; varying vec4 vLineColor; varying vec2 unitPosition; varying float innerUnitRadius; varying float outerRadiusPixels; void main(void) { geometry.worldPosition = vec3(instancePositions, 0.); // Multiply out radius and clamp to limits outerRadiusPixels = clamp( project_size_to_pixel(radiusScale * instanceRadius), radiusMinPixels, radiusMaxPixels ); // Multiply out line width and clamp to limits float lineWidthPixels = clamp( project_size_to_pixel(lineWidthScale * instanceLineWidths), lineWidthMinPixels, lineWidthMaxPixels ); // outer radius needs to offset by half stroke width outerRadiusPixels += stroked * lineWidthPixels / 2.0; // position on the containing square in [-1, 1] space unitPosition = positions.xy; geometry.uv = unitPosition; geometry.pickingColor = instancePickingColors; innerUnitRadius = 1.0 - stroked * lineWidthPixels / outerRadiusPixels; vec3 offset = positions * project_pixel_size(outerRadiusPixels); DECKGL_FILTER_SIZE(offset, geometry); gl_Position = project_position_to_clipspace(vec3(instancePositions, 0.), vec3(instancePositions64Low, 0.), offset, geometry.position); DECKGL_FILTER_GL_POSITION(gl_Position, geometry); // Apply opacity to instance color, or return instance picking color vFillColor = vec4(instanceFillColors.rgb, instanceFillColors.a * opacity); DECKGL_FILTER_COLOR(vFillColor, geometry); vLineColor = vec4(instanceLineColors.rgb, instanceLineColors.a * opacity); DECKGL_FILTER_COLOR(vLineColor, geometry); } `;
0
rapidsai_public_repos/node/modules/demo/ipc/umap/layers
rapidsai_public_repos/node/modules/demo/ipc/umap/layers/node/node-layer.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. // 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. import { Layer, project32, picking } from '@deck.gl/core'; import GL from '@luma.gl/constants'; import { Model, Geometry } from '@luma.gl/core'; import vs from './node-layer-vertex.glsl'; import fs from './node-layer-fragment.glsl'; const DEFAULT_COLOR = [0, 0, 0, 255]; const defaultProps = { radiusScale: { type: 'number', min: 0, value: 1 }, radiusMinPixels: { type: 'number', min: 0, value: 0 }, // min point radius in pixels radiusMaxPixels: { type: 'number', min: 0, value: Number.MAX_SAFE_INTEGER }, // max point radius in pixels lineWidthUnits: 'meters', lineWidthScale: { type: 'number', min: 0, value: 1 }, lineWidthMinPixels: { type: 'number', min: 0, value: 0 }, lineWidthMaxPixels: { type: 'number', min: 0, value: Number.MAX_SAFE_INTEGER }, stroked: false, filled: true, getPosition: { type: 'accessor', value: x => x.position }, getRadius: { type: 'accessor', value: 1 }, getFillColor: { type: 'accessor', value: DEFAULT_COLOR }, getLineColor: { type: 'accessor', value: DEFAULT_COLOR }, getLineWidth: { type: 'accessor', value: 1 }, // deprecated strokeWidth: { deprecatedFor: 'getLineWidth' }, outline: { deprecatedFor: 'stroked' }, getColor: { deprecatedFor: ['getFillColor', 'getLineColor'] } }; export default class NodeLayer extends Layer { getShaders(id) { return super.getShaders({ vs, fs, modules: [project32, picking] }); } initializeState() { this.getAttributeManager().addInstanced({ instancePositions: { size: 2, type: GL.FLOAT, fp64: this.use64bitPositions(), transition: false, accessor: 'getPosition' }, instanceRadius: { size: 1, transition: false, accessor: 'getRadius', type: GL.UNSIGNED_BYTE, defaultValue: 1 }, instanceFillColors: { size: this.props.colorFormat.length, transition: false, normalized: true, type: GL.UNSIGNED_BYTE, accessor: 'getFillColor', defaultValue: [0, 0, 0, 255] }, instanceLineColors: { size: this.props.colorFormat.length, transition: false, normalized: true, type: GL.UNSIGNED_BYTE, accessor: 'getLineColor', defaultValue: [0, 0, 0, 255] }, instanceLineWidths: { size: 1, transition: false, accessor: 'getLineWidth', defaultValue: 1 } }); } updateState({ props, oldProps, changeFlags }) { super.updateState({ props, oldProps, changeFlags }); if (changeFlags.extensionsChanged) { const { gl } = this.context; if (this.state.model) { this.state.model.delete(); } this.setState({ model: this._getModel(gl) }); this.getAttributeManager().invalidateAll(); } } draw({ uniforms }) { const { viewport } = this.context; const { radiusScale, radiusMinPixels, radiusMaxPixels, stroked, filled, lineWidthUnits, lineWidthScale, lineWidthMinPixels, lineWidthMaxPixels } = this.props; const widthMultiplier = lineWidthUnits === 'pixels' ? viewport.metersPerPixel : 1; this.state.model .setUniforms(uniforms) .setUniforms({ stroked: stroked ? 1 : 0, filled, radiusScale, radiusMinPixels, radiusMaxPixels, lineWidthScale: lineWidthScale * widthMultiplier, lineWidthMinPixels, lineWidthMaxPixels }) .draw(); } _getModel(gl) { // a square that minimally cover the unit circle const positions = [-1, -1, 0, -1, 1, 0, 1, 1, 0, 1, -1, 0]; return new Model( gl, Object.assign(this.getShaders(), { id: this.props.id, geometry: new Geometry({ drawMode: GL.TRIANGLE_FAN, vertexCount: 4, attributes: { positions: { size: 3, value: new Float32Array(positions) } } }), isInstanced: true }) ); } } NodeLayer.layerName = 'NodeLayer'; NodeLayer.defaultProps = defaultProps;
0
rapidsai_public_repos/node/modules/demo/sql
rapidsai_public_repos/node/modules/demo/sql/sql-cluster-server/package.json
{ "private": true, "name": "@rapidsai/demo-sql-cluster-server", "version": "22.12.2", "license": "Apache-2.0", "author": "NVIDIA, Inc. (https://nvidia.com/)", "maintainers": [ "Paul Taylor <[email protected]>" ], "bin": "index.js", "scripts": { "dev": "NODE_ENV=development node index.js", "build": "next build", "start": "next build && NODE_ENV=production node index.js" }, "dependencies": { "@material-ui/core": "4.12.3", "@material-ui/icons": "4.11.2", "@material-ui/lab": "4.0.0-alpha.60", "@material-ui/pickers": "3.3.10", "@rapidsai/cudf": "~22.12.2", "@rapidsai/sql": "~22.12.2", "apache-arrow": "^9.0.0", "axios": "0.22.0", "bootstrap": "4.6.0", "fastify-arrow": "1.0.0", "fastify-nextjs": "6.0.0", "material-ui-confirm": "2.1.3", "react": "17.0.2", "react-awesome-query-builder": "4.4.3", "react-bootstrap": "1.6.1", "react-dom": "17.0.2", "react-loading-overlay": "1.0.1" }, "files": [ "pages", "components", "data.js", "index.js", "README.md", "package.json", "next.config.js" ] }
0
rapidsai_public_repos/node/modules/demo/sql
rapidsai_public_repos/node/modules/demo/sql/sql-cluster-server/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. const fs = require('fs'); const {performance} = require('perf_hooks'); const {RecordBatchStreamWriter} = require('apache-arrow'); const {SQLCluster} = require('@rapidsai/sql'); const {DataFrame, scope} = require('@rapidsai/cudf'); const fastify = require('fastify')({ pluginTimeout: 30000, logger: process.env.NODE_ENV !== 'production', keepAliveTimeout: 0, }); const DATA_PATHS = Array.from({length: 10}, (_, i) => `${__dirname}/data/wiki_page_${i}.csv`); DATA_PATHS.forEach((DATA_PATH) => { if (!fs.existsSync(DATA_PATH)) { console.error(` .csv data not found! Run this to download the dataset from AWS S3 (16.0 GB): node ${__dirname}/data.js `); process.exit(1); } }) let sqlCluster; // Change cwd to the example dir so relative file paths are resolved process.chdir(__dirname); fastify.register((require('fastify-arrow'))) .register(require('fastify-nextjs', { dev: process.env.NODE_ENV !== 'production', })) .register(async (instance, opts, done) => { const logPath = `${__dirname}/.logs`; require('rimraf').sync(logPath); fs.mkdirSync(logPath, {recursive: true}); sqlCluster = await SQLCluster.init({ numWorkers: Infinity, enableLogging: true, // allocationMode: 'pool_memory_resource', configOptions: { PROTOCOL: 'TCP', ENABLE_TASK_LOGS: true, ENABLE_COMMS_LOGS: true, ENABLE_OTHER_ENGINE_LOGS: true, ENABLE_GENERAL_ENGINE_LOGS: true, BLAZING_LOGGING_DIRECTORY: logPath, BLAZING_LOCAL_LOGGING_DIRECTORY: logPath, } }); await sqlCluster.createCSVTable('test_table', DATA_PATHS); done(); }) .after(() => { fastify.next('/'); fastify.post('/run_query', async function(request, reply) { try { request.log.info({query: request.body}, `calling sqlCluster.sql()`); await scope(async () => { const t0 = performance.now(); const dfs = await toArray(sqlCluster.sql(request.body)).catch((err) => { request.log.error({err}, `Error calling sqlCluster.sql`); return new DataFrame(); }); const t1 = performance.now(); const queryTime = t1 - t0; const {result, rowCount} = head(dfs, 500); const arrowTable = result.toArrow(); arrowTable.schema.metadata.set('queryTime', queryTime); arrowTable.schema.metadata.set('queryResults', rowCount); RecordBatchStreamWriter.writeAll(arrowTable).pipe(reply.stream()); }); } catch (err) { request.log.error({err}, '/run_query error'); reply.code(500).send(err); } }); }); fastify.listen(3000, '0.0.0.0', err => { if (err) throw err console.log('Server listening on http://localhost:3000') }); function head(dfs, rows) { let result = new DataFrame(); let rowCount = 0; for (let i = 0; i < dfs.length; ++i) { if (dfs[i].numRows > 0) { rowCount += dfs[i].numRows; if (result.numRows <= rows) { result = scope(() => { // return result.concat(dfs[i].head(rows - result.numRows)); }); } } } return {result, rowCount}; } async function toArray(src) { const dfs = []; for await (const df of src) { dfs.push(df); } return dfs; }
0
rapidsai_public_repos/node/modules/demo/sql
rapidsai_public_repos/node/modules/demo/sql/sql-cluster-server/data.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. const axios = require('axios').default; const fs = require('fs'); const zlib = require('zlib'); module.exports = DownloadSQLClusterServerDataSet; if (require.main === module) { // module.exports().catch((e) => console.error(e) || process.exit(1)); } async function DownloadSQLClusterServerDataSet() { if (!fs.existsSync(`${__dirname}/data`)) { fs.mkdirSync(`${__dirname}/data`); } console.log('Downloading dataset...'); for (let i = 0; i < 10; ++i) { await DownloadChunk(i); } } async function DownloadChunk(index) { await axios .get(`https://node-rapids-data.s3.us-west-2.amazonaws.com/wikipedia/page_titles_en_${ index}.csv.gz`, {responseType: 'stream'}) .then(function(response) { response.data.pipe(zlib.createGunzip()) .pipe(fs.createWriteStream(`${__dirname}/data/wiki_page_${index}.csv`)); }) .catch(function(error) { console.log(error); }) .then() }
0
rapidsai_public_repos/node/modules/demo/sql
rapidsai_public_repos/node/modules/demo/sql/sql-cluster-server/README.md
# SQLCluster Server Demo This demo demonstrates the SQLCluster module which allows for multi-GPU SQL queries using our SQL engine. ## Main Dependencies - @rapidsai/sql - fastify-nextjs - react-awesome-query-builder ## Installation To install dependencies, run the following from the root directory for `node-rapids` ```bash yarn ``` To run the demo ```bash # Select the sql-cluster-server demo from the list of demos yarn demo # OR specifically with cd modules/demo/sql/sql-cluster-server yarn start ``` ## Dataset The dataset used for this demo is the entire collection of **2021 English Wikipedia** pages. This includes the following for each page... 1. Page ID 2. Revision ID 3. Page URL 4. Page Title 5. Page Text This ends up totaling to about ~17GB (uncompressed) worth of data. *NOTE*: because of a limit to the maximum amount of characters in a cuDF dataframe, the dataset will be broken up into several 1.7GB files. ### Dataset Extraction There are quite a lot of outdated tutorials on how to extract Wikipedia data that no longer work. The method here was the only one that was successful. 1. Visit https://dumps.wikimedia.org/enwiki/latest/ and download `enwiki-latest-pages-articles.xml.bz2`. There are various other locations available as well to download the latest wikipedia pages-article dump. 2. Extract the wikipedia pages-article dump (this should be a `.xml` file) 3. We will be using this tool to extract the wikipedia pages-article `.xml` file https://github.com/attardi/wikiextractor 4. Clone the `wikiextractor` repo and follow the insallation instructions to be able to run the script locally. 5. Move the extracted wikipedia page-article `.xml` file inside of your `wikiextractor` cloned directory 6. You can follow the `README.md` on the `wikiextractor` page for additional arguments to run the script 7. Use your own specific command args or use the following... ```bash python -m wikiextractor.WikiExtractor --json enwiki-20210901-pages-articles-multistream.xml ``` The running of this command should create a `text` folder which will contain multiple folders inside. These folders contain wikipedia page data in `.json` form. From here you can simply use a python script to parse the data in the form you need it in. ## Interesting Queries Using the query builder you can seamlessly build queries and execute them against our dataset. Here are some interesting queries if you need some inspiration... - Who appears in more Wikipedia pages, Plato or Newton? - Select `text`, using the `like` operator, type in `Plato`/`Newton` and check out how many results are returned. - Which programming language is referenced the most across all Wikipedia pages? - Select `text`, using the `like` operator, type in your favorite programming language and see how popular it is. - Is there any Wikipedia page that avoids using the most common english word `the`? - Select `text`, using the `Is not empty` operator - Click `ADD GROUP`, select `text`, using the `not like` operator, type in `the`. - How many Wikipedia pages have your first name in the `title`? - Select `title`, using the `like` operator, type in your first name. - How many Wikipedia pages are redirects to other pages? - Select `text`, using the `Is empty` operator.
0
rapidsai_public_repos/node/modules/demo/sql
rapidsai_public_repos/node/modules/demo/sql/sql-cluster-server/next.config.js
module.exports = { eslint: { ignoreDuringBuilds: true, } }
0
rapidsai_public_repos/node/modules/demo/sql/sql-cluster-server
rapidsai_public_repos/node/modules/demo/sql/sql-cluster-server/components/querybuilder.jsx
// 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 'react-awesome-query-builder/lib/css/styles.css'; import * as React from 'react'; import { Builder, Query, Utils as QbUtils } from 'react-awesome-query-builder'; import MaterialConfig from 'react-awesome-query-builder/lib/config/material'; const config = { ...MaterialConfig, fields: { id: { label: 'id', type: 'number', valueSources: ['value'], preferWidgets: ['number'], }, revid: { label: 'revid', type: 'number', valueSources: ['value'], preferWidgets: ['number'], }, url: { label: 'url', type: 'text', valueSources: ['value'], excludeOperators: ["proximity", "equal", "not_equal"], mainWidgetProps: { valueLabel: "url", valuePlaceholder: "Enter url", }, }, title: { label: 'title', type: 'text', valueSources: ['value'], excludeOperators: ["proximity", "equal", "not_equal"], mainWidgetProps: { valueLabel: "title", valuePlaceholder: "Enter title", }, }, text: { label: 'text', type: 'text', valueSources: ['value'], excludeOperators: ["proximity", "equal", "not_equal"], mainWidgetProps: { valueLabel: "text", valuePlaceholder: "Enter text", }, } } }; const queryValue = { 'id': '9a99988a-0123-4456-b89a-b1607f326fd8', 'type': 'group', 'children1': { 'a98ab9b9-cdef-4012-b456-71607f326fd9': { 'type': 'rule', 'properties': { field: null, operator: null, value: [], valueSrc: [], 'type': 'rule', } } } }; export class QueryBuilder extends React.Component { constructor() { super(); this.state = { tree: QbUtils.checkTree(QbUtils.loadTree(queryValue), config), config: config, }; } render = () => (<div><Query{...config} value={this.state.tree} onChange={ this.onChange} renderBuilder={this.renderBuilder} /> </div>) renderBuilder = (props) => ( <div className='query-builder-container'> <div className='query-builder qb-lite'> <Builder { ...props} /> </div> </div> ) onChange = (immutableTree, config) => { this.setState({ tree: immutableTree, config: config }); this.props.onQueryChange(this._parseQuery(JSON.stringify(QbUtils.sqlFormat(immutableTree, config)))); } _parseQuery(query) { if (query === undefined || query.length == 0) return ''; // Hacky, but the sql builder uses 'NOT EMPTY' and 'EMPTY' when constructing the query. // Let's just replace any instances with 'NOT NULL' and 'NULL'. query = query.replace('NOT EMPTY', 'NOT NULL'); query = query.replace('EMPTY', 'NULL'); return `SELECT id, revid, url, title, text FROM test_table WHERE ${JSON.parse(query)}`; } }
0
rapidsai_public_repos/node/modules/demo/sql/sql-cluster-server
rapidsai_public_repos/node/modules/demo/sql/sql-cluster-server/components/querydashboard.jsx
// 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 Button from '@material-ui/core/Button'; import * as React from 'react'; import { Col, Container, FormControl, InputGroup, Row } from 'react-bootstrap'; import { QueryBuilder } from './querybuilder'; import { tableFromIPC } from 'apache-arrow'; import Paper from '@material-ui/core/Paper'; import MatTable from '@material-ui/core/Table'; import TableBody from '@material-ui/core/TableBody'; import TableCell from '@material-ui/core/TableCell'; import TableContainer from '@material-ui/core/TableContainer'; import TableHead from '@material-ui/core/TableHead'; import TablePagination from '@material-ui/core/TablePagination'; import TableRow from '@material-ui/core/TableRow'; import Typography from '@material-ui/core/Typography'; import LoadingOverlay from 'react-loading-overlay'; const MAX_RESULTS_TO_DISPLAY = 500; const columns = [ { id: 'id', label: 'ID', minWidth: 0, }, { id: 'revid', label: 'Rev ID', minWidth: 0, }, { id: 'url', label: 'URL', minWidth: 0, }, { id: 'title', label: 'Title', minWidth: 0, }, { id: 'text', label: 'Text', minWidth: 500 } ]; /** * * @param {import('apache-arrow').Table} table */ function formatData(table) { let rows = []; if (table.length == 0) { return rows; } const resultsToDisplay = table.length < MAX_RESULTS_TO_DISPLAY ? table.length : MAX_RESULTS_TO_DISPLAY; const ids = [...table.getChild("id") || []].map(Number).slice(0, resultsToDisplay); const revids = [...table.getChild("revid") || []].map(Number).slice(0, resultsToDisplay); const urls = [...table.getChild("url") || []].slice(0, resultsToDisplay); const titles = [...table.getChild("title") || []].slice(0, resultsToDisplay); const texts = [...table.getChild("text") || []].slice(0, resultsToDisplay); for (let i = 0; i < resultsToDisplay; ++i) { rows.push({ id: ids[i] || '', revid: revids[i] || '', url: urls[i] || '', title: titles[i] || '', text: texts[i] || '', }); } return rows; } export class QueryDashboard extends React.Component { constructor() { super(); this.state = { query: '', queryTime: '', queryResult: [], queryButtonEnabled: false, runningQuery: false, page: 0, rowsPerPage: 10, }; this.runQuery = this.runQuery.bind(this); } onQueryChange = (updatedQuery) => { this.setState({ query: updatedQuery, queryButtonEnabled: updatedQuery.length }); } async runQuery() { if (this.state.queryButtonEnabled) { this.setState({ runningQuery: true, queryButtonEnabled: false }); await fetch(`/run_query`, { method: `POST`, headers: { 'accepts': `application/octet-stream` }, body: `${this.state.query}` }).then((res) => tableFromIPC(res)).then((table) => { this.setState({ queryResult: formatData(table), queryTime: table.schema.metadata.get('queryTime'), resultCount: table.schema.metadata.get('queryResults'), page: 0, rowsPerPage: 10 }); }); this.setState({ runningQuery: false, queryButtonEnabled: true }); } } handleChangePage = (event, newPage) => { this.setState({ page: newPage }); }; handleChangeRowsPerPage = (event) => { this.setState({ rowsPerPage: +event.target.value, page: 0 }); }; render() { return ( <Container style={{ paddingTop: 40 }}> <LoadingOverlay active={this.state.runningQuery} spinner text='Running query...' > <QueryBuilder onQueryChange={ this.onQueryChange} /> </LoadingOverlay> <Row style={{ marginTop: 20, marginBottom: 20 }}> <Col lg={9} md={9} sm={8} xs={8}> <InputGroup className={"queryInput"}> <div className="input-group-prepend"> <span className="input-group-text">Query: </span> </div> <FormControl className={"queryInput"} value={this.state.query} disabled={true} type={"text"} /> </InputGroup> </Col> <Col> <Button variant='contained' color='primary' className={'queryButton'} disabled={!this.state.queryButtonEnabled} onClick={this.runQuery}>Run Query</Button> </Col> </Row> <Paper> <Typography style={{ marginLeft: 5 }} variant="h6" id="tableTitle" component="div"> <div>Query Time: {Math.round(this.state.queryTime)} ms</div> <div>Results: {this.state.resultCount ?? 0}</div> </Typography> <TableContainer> <MatTable stickyHeader aria-label="sticky table"> <TableHead> <TableRow> {columns.map((column) => ( <TableCell key={column.id} align={column.align} style={{ minWidth: column.minWidth }} > {column.label} </TableCell> ))} </TableRow> </TableHead> <TableBody> {this.state.queryResult.slice(this.state.page * this.state.rowsPerPage, this.state.page * this.state.rowsPerPage + this.state.rowsPerPage).map((row) => { return ( <TableRow hover role="checkbox" tabIndex={-1} key={row.code}> {columns.map((column) => { const value = row[column.id]; return ( <TableCell key={column.id} align={column.align}> <div style={{ display: 'block', textOverflow: 'ellipsis', overflow: 'hidden', maxHeight: 100 }}> {column.format && typeof value === 'number' ? column.format(value) : value} </div> </TableCell> ); })} </TableRow> ); })} </TableBody> </MatTable> </TableContainer> <TablePagination rowsPerPageOptions={[10, 25, 100, 500]} component="div" count={this.state.queryResult.length} rowsPerPage={this.state.rowsPerPage} page={this.state.page} onPageChange={this.handleChangePage} onRowsPerPageChange={this.handleChangeRowsPerPage} /> <div style={{ textAlign: "end", paddingRight: "20px", paddingBottom: "5px", fontSize: "12px", color: "grey" }}> (Table only displays 500 results max) </div> </Paper> </Container > ) } }
0
rapidsai_public_repos/node/modules/demo/sql/sql-cluster-server
rapidsai_public_repos/node/modules/demo/sql/sql-cluster-server/pages/style.css
/* 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. */ body { background-color: #212121!important; margin-bottom: 40px; } .navbar { background-color: #7300ff!important; font-weight: bold; } .customCol { padding: 20px !important; padding-bottom: 0px !important; } /* Query Builder Padding/Margin removal */ .query-builder { margin: 0px !important; } .group-or-rule-container { padding-right: 0px !important; } .rule, .group-or-rule { padding-right: 10px !important; } /* Right Column */ .queryButton { width: 100% !important; height: 50px !important; } .MuiButton-contained.Mui-disabled { background-color: rgb(122, 122, 122) !important; } .queryInput { height: 50px !important; }
0
rapidsai_public_repos/node/modules/demo/sql/sql-cluster-server
rapidsai_public_repos/node/modules/demo/sql/sql-cluster-server/pages/_app.jsx
// 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 'bootstrap/dist/css/bootstrap.min.css'; import './style.css'; import { Container, Navbar, Nav } from 'react-bootstrap'; import { QueryDashboard } from '../components/querydashboard'; import * as React from 'react'; export default function App() { return ( <div> <Navbar bg="dark" variant="dark"> <Container> <Navbar.Brand className={"navbar"}>node-rapids │ SQLCluster Server Demo</Navbar.Brand> <Nav> <Nav.Link href="https://github.com/rapidsai/node">node-rapids github</Nav.Link> </Nav> </Container> </Navbar> <QueryDashboard /> </div > ) }
0
rapidsai_public_repos/node/modules/demo
rapidsai_public_repos/node/modules/demo/viz-app/package.json
{ "name": "@rapidsai/demo-viz-app", "version": "22.12.2", "private": true, "author": "NVIDIA, Inc. (https://nvidia.com/)", "maintainers": [ "Ajay Thorve([email protected])" ], "bin": "index.js", "scripts": { "dev": "next dev", "build": "next build", "start": "next build && next start" }, "dependencies": { "@deck.gl/carto": "8.8.10", "@deck.gl/core": "8.8.10", "@deck.gl/geo-layers": "8.8.10", "@deck.gl/layers": "8.8.10", "@deck.gl/mesh-layers": "8.8.10", "@deck.gl/react": "8.8.10", "@fortawesome/fontawesome-svg-core": "1.2.35", "@fortawesome/free-solid-svg-icons": "5.15.3", "@fortawesome/react-fontawesome": "0.1.14", "@rapidsai/cudf": "~22.12.2", "apache-arrow": "^9.0.0", "bootstrap": "4.6.0", "d3": "6.6.2", "echarts": "5.0.2", "echarts-for-react": "3.0.1", "mjolnir.js": "2.7.1", "next": "11.1.3", "react": "17.0.2", "react-bootstrap": "1.6.1", "react-burger-menu": "3.0.6", "react-dom": "17.0.2", "react-table": "7.7.0", "react-tabs": "3.2.2", "simple-peer": "9.11.0", "socket.io-client": "4.2.0" }, "files": [ "pages", "styles", "components", "next.config.js", "package.json" ] }
0
rapidsai_public_repos/node/modules/demo
rapidsai_public_repos/node/modules/demo/viz-app/index.js
#!/usr/bin/env -S node --trace-uncaught // 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. const Path = require('path'); // Change cwd to the example dir so relative file paths are resolved process.chdir(__dirname); const next = require.resolve('next/dist/bin/next'); require('fs').stat(Path.join(__dirname, '.next'), (err, stats) => { const {spawnSync} = require('child_process'); const env = { NEXT_TELEMETRY_DISABLED: 1, // disable https://nextjs.org/telemetry ...process.env, }; if (err || !stats || !stats.isDirectory()) { spawnSync(process.execPath, [next, 'build'], {env, cwd: __dirname, stdio: 'inherit'}); } spawnSync(process.execPath, [next, 'start'], {env, cwd: __dirname, stdio: 'inherit'}); });
0
rapidsai_public_repos/node/modules/demo
rapidsai_public_repos/node/modules/demo/viz-app/README.md
# Server-Side Rendered Visualization App Frontend [WIP] A front end application connected to the [SSR](https://github.com/rapidsai/node/tree/main/modules/demo/ssr) compute, rendering, and streaming backend. The visualizations are all streamed to a `<video>` tag. ## Featured Dependencies - React ## Data Requirements The front end has no explicit data requirements. ## Start Running the viz-app requires two terminal instances, then opening to `localhost:3000`, and selection your viz type: ```bash # Terminal 1 - start the rendering server: yarn demo modules/demo/ssr/graph #/luma /point-cloud # Terminal 2 - start the front end visualization app: yarn demo modules/demo/viz-app ```
0
rapidsai_public_repos/node/modules/demo
rapidsai_public_repos/node/modules/demo/viz-app/next.config.js
module.exports = { eslint: { ignoreDuringBuilds: true, }, }
0
rapidsai_public_repos/node/modules/demo/viz-app
rapidsai_public_repos/node/modules/demo/viz-app/styles/global.css
/* 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. */ html, #__next, .jumbotron { background-color: #121212 !important; } a { color: rgb(207, 207, 207) !important; text-decoration: underline !important; } a:hover { color: rgb(172, 172, 172) !important; } .max { width: 100%; } /* Buttons */ .textButton { color: black; user-select: none; } .textButton:hover { color: rgb(83, 83, 83); cursor: pointer; } .textButton:active { color: black; } .whiteTextButton { color: white; user-select: none; } .whiteTextButton:hover { color: rgb(204, 204, 204); cursor: pointer; } .whiteTextButton:active { color: white; } /* */ /* Tabs */ .react-tabs { -webkit-tap-highlight-color: transparent; } .react-tabs__tab-list { margin: 0 0 0 0; padding: 0; } .react-tabs__tab { display: inline-block; border: 1px solid; border-bottom: 3px; bottom: -1px; position: relative; list-style: none; padding: 6px 12px; cursor: pointer; background: #202020; margin-right: 3px; margin-bottom: 1px; font-size: 14px; font-weight: bold; border-radius: 5px 5px 0 0; border-color: #202020; color: rgb(204, 204, 204); } .react-tabs__tab--selected { background: #363636; border-color: #363636; color: white; border-bottom: 1px solid #363636; } .react-tabs__tab--disabled { color: GrayText; cursor: default; } .react-tabs__tab:focus { outline: none; } .react-tabs__tab:focus:after { position: absolute; } .react-tabs__tab-panel { display: none; background: #363636 !important; } .react-tabs__tab-panel--selected { display: block; } /* */ /* NavBar Menu */ .bm-burger-button { position: absolute; width: 36px; height: 30px; top: 12px; left: 12px; } .bm-burger-bars { background: white; } .bm-burger-bars-hover { background: rgb(204, 204, 204); } .bm-cross-button { height: 24px; width: 24px; } .bm-cross { background-color: white; } .bm-menu-wrap { position: absolute; height: 100%; } .bm-menu { background: #363636; padding: 2.5em 1em 0; font-size: 1.15em; border-right: 3px solid #121212; } .bm-morph-shape { fill: #373a47; } .bm-item-list { color: #b8b7ad; padding: 0.8em; } .bm-item { display: inline-block; } .bm-overlay { background: rgba(0, 0, 0, 0.3); } .menu-item { color: black; border-bottom: 1px solid black; font-size: 23px; line-height: 13px; padding-bottom: 8px; } /* */
0
rapidsai_public_repos/node/modules/demo/viz-app/components
rapidsai_public_repos/node/modules/demo/viz-app/components/demo-dashboard/demo-dashboard.jsx
// 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 * as React from 'react'; import Layout from './layout/layout'; import DemoView from './demo-view/demo-view'; import DataRow from './data-row/data-row'; import Footer from './footer/footer'; import { Container } from 'react-bootstrap'; import SlideMenu from './slide-menu/slide-menu'; export default class DemoDashboard extends React.Component { render() { const { demoName, isLoading } = this.props; return ( <div id="outer-container"> <SlideMenu onLoadClick={this.props.onLoadClick} onRenderClick={this.props.onRenderClick} /> <Layout id="page-wrap" title={demoName} isLoading={isLoading}> <DemoView demoView={this.props.demoView} /> <Container fluid style={{ paddingTop: 20 }}> <DataRow dataTable={this.props.dataTable} dataMetrics={this.props.dataMetrics} /> <Footer /> </Container> </Layout> </div> ) } }
0
rapidsai_public_repos/node/modules/demo/viz-app/components/demo-dashboard
rapidsai_public_repos/node/modules/demo/viz-app/components/demo-dashboard/file-input/file-input.jsx
// 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 * as React from 'react'; export default class FileInput extends React.Component { constructor(props) { super(props) this.uploadFile = this.uploadFile.bind(this); } uploadFile(event) { let file = event.target.files[0]; this.props.onChange(file.name); } render() { return <label style={{ width: 130, height: 0 }}> <p className={this.props?.useWhite ? "whiteTextButton" : "textButton"}>{this.props.children}</p> <input type="file" style={{ display: "none" }} onChange={this.uploadFile} /> </label> } }
0
rapidsai_public_repos/node/modules/demo/viz-app/components/demo-dashboard
rapidsai_public_repos/node/modules/demo/viz-app/components/demo-dashboard/layout/layout.jsx
// 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 styles from './layout.module.css' import CustomNavbar from '../navbar/navbar' export default function Layout({ title, children, resetall, displayReset, isLoading }) { return ( <> <CustomNavbar title={title} resetall={resetall} displayReset={displayReset} isLoading={isLoading}></CustomNavbar> <div className={styles.container}> {children} </div> </> ) }
0
rapidsai_public_repos/node/modules/demo/viz-app/components/demo-dashboard
rapidsai_public_repos/node/modules/demo/viz-app/components/demo-dashboard/layout/layout.module.css
/* 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. */ .container { width: 100%; height: 80%; }
0
rapidsai_public_repos/node/modules/demo/viz-app/components/demo-dashboard
rapidsai_public_repos/node/modules/demo/viz-app/components/demo-dashboard/slide-menu/slide-menu.jsx
// 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 * as React from 'react'; import FileInput from '../file-input/file-input'; import HeaderUnderline from '../header-underline/header-underline'; import { slide as Menu } from 'react-burger-menu'; import { Row, Col } from 'react-bootstrap'; export default class SlideMenu extends React.Component { constructor(props) { super(props) this.state = { selectedFilePath: "", } this.onDataChange = this.onDataChange.bind(this); this.onLoadClick = this.onLoadClick.bind(this); this.onRenderClick = this.onRenderClick.bind(this); } onDataChange(filePath) { this.setState({ selectedFilePath: filePath }); } onLoadClick() { this.props.onLoadClick(this.state.selectedFilePath); } onRenderClick() { this.props.onRenderClick(); } render() { return ( <Menu pageWrapId={"page-wrap"} outerContainerId={"outer-container"} width={'50vw'}> <HeaderUnderline title={"Data Source"} color={"white"}> <Row> <Col className={"col-auto"}> <FileInput onChange={this.onDataChange} useWhite={true}> Select Data ▼ </FileInput> <p style={{ color: "white" }}>Selection: {this.state.selectedFilePath}</p> </Col> <Col className={"max"} ><div className={"d-flex"} /></Col> <Col className={"col-auto"}> <p className={"whiteTextButton"} onClick={this.onLoadClick}>[Load]</p> </Col> </Row> </HeaderUnderline> <div style={{ height: 20 }} /> <HeaderUnderline title={"Visualization"} color={"white"}> <p className={"whiteTextButton"} onClick={this.onRenderClick}>[Render]</p> </HeaderUnderline> </Menu > ); } }
0
rapidsai_public_repos/node/modules/demo/viz-app/components/demo-dashboard
rapidsai_public_repos/node/modules/demo/viz-app/components/demo-dashboard/data-row/data-container.module.css
/* 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. */ .container { background-color: #252525; height: 100%; }
0
rapidsai_public_repos/node/modules/demo/viz-app/components/demo-dashboard
rapidsai_public_repos/node/modules/demo/viz-app/components/demo-dashboard/data-row/data-row.jsx
// 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 * as React from 'react'; import { Row, Col } from 'react-bootstrap'; import DataTable from './data-table/data-table'; import DataMetrics from './data-metrics/data-metrics'; export default function DataRow({ dataTable, dataMetrics }) { return ( <Row style={{ marginBottom: 10 }}> {dataTable != undefined && <Col xs={12} sm={dataMetrics == undefined ? 12 : 8}> <DataTable source={dataTable} /> </Col> } <Col> <DataMetrics source={dataMetrics} /> </Col> </Row> ) }
0
rapidsai_public_repos/node/modules/demo/viz-app/components/demo-dashboard/data-row
rapidsai_public_repos/node/modules/demo/viz-app/components/demo-dashboard/data-row/data-metrics/data-metrics.jsx
// 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 * as React from 'react'; import styles from '../data-container.module.css'; export default function DataMetrics({ source }) { return ( <div className={styles.container}> {source} </div> ) }
0
rapidsai_public_repos/node/modules/demo/viz-app/components/demo-dashboard/data-row
rapidsai_public_repos/node/modules/demo/viz-app/components/demo-dashboard/data-row/data-table/data-table.jsx
// 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 * as React from 'react'; import styles from '../data-container.module.css'; export default function DataTable({ source }) { return ( <div className={styles.container}> {source} </div> ) }
0
rapidsai_public_repos/node/modules/demo/viz-app/components/demo-dashboard
rapidsai_public_repos/node/modules/demo/viz-app/components/demo-dashboard/navbar/navbar.module.css
/* 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. */ .navbar{ background-color: #363636 !important; border-bottom: 3px solid #121212; } .title { color: white; font-weight: bold; padding-left: 45px; }
0
rapidsai_public_repos/node/modules/demo/viz-app/components/demo-dashboard
rapidsai_public_repos/node/modules/demo/viz-app/components/demo-dashboard/navbar/navbar.jsx
// 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 styles from './navbar.module.css'; import Navbar from 'react-bootstrap/Navbar'; import Status from './status/status'; export default function CustomNavbar({ title, isLoading }) { return ( <Navbar bg="dark" variant="dark" className={styles.navbar}> <Navbar.Brand> <div className={styles.title}> {title} </div> </Navbar.Brand> <Navbar className={"mr-auto"}></Navbar> <Status isLoading={isLoading} /> </Navbar > ) }
0
rapidsai_public_repos/node/modules/demo/viz-app/components/demo-dashboard/navbar
rapidsai_public_repos/node/modules/demo/viz-app/components/demo-dashboard/navbar/status/status.jsx
// 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 * as React from 'react'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faCircleNotch } from '@fortawesome/free-solid-svg-icons'; export default function Status({ isLoading }) { return ( <div style={{ fontSize: 20, color: "white" }}> {isLoading ? `Loading` : `Ready`} <FontAwesomeIcon spin={isLoading} icon={faCircleNotch} /> </div> ); }
0
rapidsai_public_repos/node/modules/demo/viz-app/components/demo-dashboard
rapidsai_public_repos/node/modules/demo/viz-app/components/demo-dashboard/header-underline/header-underline.jsx
// 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 * as React from 'react'; export default function HeaderUnderline(props) { return ( <div> <div className={"menu-item"} style={{ marginBottom: 5, fontSize: props.fontSize, color: props.color, borderBottomColor: props.color }}> {props.title} </div> {props.children} </div> ); }
0
rapidsai_public_repos/node/modules/demo/viz-app/components/demo-dashboard
rapidsai_public_repos/node/modules/demo/viz-app/components/demo-dashboard/tool-bar/tool-bar.jsx
// 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 * as React from 'react'; import styles from './tool-bar.module.css'; import Image from 'next/image'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faVectorSquare, faDrawPolygon, faMousePointer, faSearchMinus, faTimes } from '@fortawesome/free-solid-svg-icons'; export default class ToolBar extends React.Component { constructor(props) { super(props) this.state = { selectedTool: 'click', } this.selectTool = this.selectTool.bind(this); } selectTool(tool) { this.setState(() => ({ selectedTool: tool })); this.props.onToolSelect(tool); } createTool(name, icon, selectedTool) { return ( <div onClick={() => { this.selectTool(name) }} className={`${styles.tool} ${selectedTool == name ? styles.selected : ''}`}> <FontAwesomeIcon icon={icon} /> </div> ); } createButton(tag, onClick) { return ( <div onClick={onClick} className={styles.tool}> {tag} </div> ) } render() { return ( <div className={styles.toolBar}> {this.createTool('boxSelect', faVectorSquare, this.state.selectedTool)} {/* {this.createTool('poly', faDrawPolygon, this.state.selectedTool)} */} {this.createTool('click', faMousePointer, this.state.selectedTool)} {/* {this.createButton(<Image src="/images/zoom.png" width={20} height={20} />, this.props.onResetClick)} */} {this.createButton(<Image src="/images/reset.png" width={20} height={20} />, this.props.onClearClick)} </div> ); } }
0
rapidsai_public_repos/node/modules/demo/viz-app/components/demo-dashboard
rapidsai_public_repos/node/modules/demo/viz-app/components/demo-dashboard/tool-bar/tool-bar.module.css
/* 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. */ .toolBar { display: inline-flex; flex-direction: column; background-color: #363636; } .tool { width: 40px; height: 40px; display: flex; justify-content: center; align-items: center; color: rgb(207, 207, 207); } .tool:hover { background-color: rgb(83, 83, 83); cursor: pointer; } .tool:active { background-color: rgb(207, 207, 207); } .selected { background-color: rgb(83, 83, 83); border: 2px solid #99d0ef; }
0
rapidsai_public_repos/node/modules/demo/viz-app/components/demo-dashboard
rapidsai_public_repos/node/modules/demo/viz-app/components/demo-dashboard/footer/footer.jsx
// 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. export default function Footer() { return ( <div> <p style={{ color: "white" }}> Powered by <a href="https://rapids.ai/">RAPIDS</a> | <a href="https://rapidsai.github.io/node/">Docs</a> | <a href="https://github.com/rapidsai/node">GitHub</a> </p> </div> ) }
0
rapidsai_public_repos/node/modules/demo/viz-app/components/demo-dashboard
rapidsai_public_repos/node/modules/demo/viz-app/components/demo-dashboard/extended-table/extended-table.jsx
// 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 * as React from 'react'; import { useTable, useSortBy, usePagination } from 'react-table'; import styles from './extended-table.module.css'; export default function ExtendedTable({ cols, data }) { const columns = cols; const { getTableProps, getTableBodyProps, headerGroups, page, prepareRow, canPreviousPage, canNextPage, pageOptions, pageCount, gotoPage, nextPage, previousPage, setPageSize, state: { pageIndex, pageSize }, } = useTable({ columns, data, initialState: { pageIndex: 0 }, }, useSortBy, usePagination); return ( <> <table className={styles.table} {...getTableProps()}> <thead> {headerGroups.map(headerGroup => ( <tr {...headerGroup.getHeaderGroupProps()}> {headerGroup.headers.map(column => ( <th className={`${styles.th} whiteTextButton`} {...column.getHeaderProps(column.getSortByToggleProps())}> {column.render('Header')} <span> {column.isSorted ? column.isSortedDesc ? ' ▼' : ' ▲' : ''} </span> </th> ))} </tr> ))} </thead> <tbody {...getTableBodyProps()}> {page.map( (row, i) => { prepareRow(row); return ( <tr className={i % 2 != 0 ? styles.grey : ''} {...row.getRowProps()}> {row.cells.map(cell => { return ( <td className={styles.td} {...cell.getCellProps()}>{cell.render('Cell')}</td> ) })} </tr> ) } )} </tbody> </table> <div className={styles.spacer}> <div /> <div className={styles.pagination}> <select className={styles.select} value={pageSize} onChange={e => { setPageSize(Number(e.target.value)) }} > {[10, 20, 30, 40, 50].map(pageSize => ( <option key={pageSize} value={pageSize}> Show {pageSize} </option> ))} </select> <div className={"whiteTextButton"} style={{ paddingRight: 5 }} onClick={() => gotoPage(0)} disabled={!canPreviousPage}> {'<<'} </div>{' '} <div className={"whiteTextButton"} style={{ paddingRight: 5 }} onClick={() => previousPage()} disabled={!canPreviousPage}> {'<'} </div>{' '} <span style={{ paddingRight: 5, color: "white" }}> <strong> {pageIndex + 1} of {pageOptions.length} </strong>{' '} </span> <div className={"whiteTextButton"} style={{ paddingRight: 5 }} onClick={() => nextPage()} disabled={!canNextPage}> {'>'} </div>{' '} <div className={"whiteTextButton"} onClick={() => gotoPage(pageCount - 1)} disabled={!canNextPage}> {'>>'} </div>{' '} </div> </div> </> ) }
0
rapidsai_public_repos/node/modules/demo/viz-app/components/demo-dashboard
rapidsai_public_repos/node/modules/demo/viz-app/components/demo-dashboard/extended-table/extended-table.module.css
/* 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. */ .table { border-spacing: 0; width: 100%; color: white; } .th { background: #2e2e2e; padding-left: 5px; } .td { padding-left: 5px; } .grey { background: #2e2e2e; } .spacer { display:flex; justify-content:space-between; } .pagination { display: flex; flex-direction: row; padding: 5px; } .select { background-color: #363636; border: none; font-weight: bold; margin-right: 8px; color: white; } .select:hover { color: rgb(204, 204, 204); cursor: pointer; } .select:active { color: white; cursor: pointer; }
0
rapidsai_public_repos/node/modules/demo/viz-app/components/demo-dashboard
rapidsai_public_repos/node/modules/demo/viz-app/components/demo-dashboard/demo-view/demo-view.jsx
// 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 styles from './demo-view.module.css'; export default function DemoView({ demoView }) { return ( <div className={styles.view}> {demoView} </div> ) }
0
rapidsai_public_repos/node/modules/demo/viz-app/components/demo-dashboard
rapidsai_public_repos/node/modules/demo/viz-app/components/demo-dashboard/demo-view/demo-view.module.css
/* 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. */ .view { height: 50vh; width: 100% !important; background-color: #191a1a; }
0
rapidsai_public_repos/node/modules/demo/viz-app/components
rapidsai_public_repos/node/modules/demo/viz-app/components/demo-card/demo-card.jsx
// 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 { Card, Button } from 'react-bootstrap'; import Link from 'next/link'; export default function DemoCard({ title, description, href }) { return ( <Card> <Card.Img variant="top" height={170} style={{ backgroundColor: "lightgrey" }} /> <Card.Body> <Card.Title>{title}</Card.Title> <Card.Text> {description} </Card.Text> <Link href={href}> <Button variant="dark">Start Demo</Button> </Link> </Card.Body> </Card> ) }
0
rapidsai_public_repos/node/modules/demo/viz-app
rapidsai_public_repos/node/modules/demo/viz-app/pages/index.jsx
// 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 DemoCard from "../components/demo-card/demo-card"; import { Container, Row, Col, Jumbotron } from 'react-bootstrap'; export default function Home() { const demos = [ { title: 'Graph', description: 'This is the description of the Graph demo.', href: '/demo/graph' }, { title: 'Point Cloud', description: 'This is the description of the Point Cloud demo.', href: '/demo/point-cloud' } ]; return ( <Jumbotron> <Container> <Row className={"justify-content-center"}> { demos.map((demo) => ( <Col xs={12} md={6} lg={4} className={"mb-4"} key={demo['title']}> <DemoCard title={demo['title']} description={demo['description']} href={demo['href']} /> </Col> )) } </Row> </Container> </Jumbotron> ) }
0
rapidsai_public_repos/node/modules/demo/viz-app
rapidsai_public_repos/node/modules/demo/viz-app/pages/_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 '../styles/global.css' import 'bootstrap/dist/css/bootstrap.min.css'; export default function App({Component, pageProps}) { return < Component { ...pageProps } /> }
0
rapidsai_public_repos/node/modules/demo/viz-app/pages
rapidsai_public_repos/node/modules/demo/viz-app/pages/demo/point-cloud.jsx
// 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 * as React from 'react'; import DemoDashboard from "../../components/demo-dashboard/demo-dashboard"; import { io } from "socket.io-client"; import SimplePeer from "simple-peer"; function onlyH264(sdp) { // remove non-h264 codecs from the supported codecs list const videos = sdp.match(/^m=video.*$/gm); if (videos) { return videos.map((video) => [video, [ ...getCodecIds(sdp, 'VP9'), ...getCodecIds(sdp, 'VP8'), ...getCodecIds(sdp, 'HEVC'), ...getCodecIds(sdp, 'H265') ]]).reduce((sdp, [video, ids]) => ids.reduce((sdp, id) => [ new RegExp(`^a=fmtp:${id}(.*?)$`, 'gm'), new RegExp(`^a=rtpmap:${id}(.*?)$`, 'gm'), new RegExp(`^a=rtcp-fb:${id}(.*?)$`, 'gm'), ].reduce((sdp, expr) => sdp.replace(expr, ''), sdp), sdp) .replace(video, ids.reduce((video, id) => video.replace(` ${id}`, ''), video)), sdp) .replace('\r\n', '\n').split('\n').map((x) => x.trim()).filter(Boolean).join('\r\n') + '\r\n'; } return sdp; function getCodecIds(sdp, codec) { return getIdsForMatcher(sdp, new RegExp( `^a=rtpmap:(?<id>\\d+)\\s+${codec}\\/\\d+$`, 'm' )).reduce((ids, id) => [ ...ids, id, ...getIdsForMatcher(sdp, new RegExp( `^a=fmtp:(?<id>\\d+)\\s+apt=${id}$`, 'm' )) ], []); } function getIdsForMatcher(sdp, matcher) { const ids = []; /** @type RegExpMatchArray */ let res, str = '' + sdp, pos = 0; for (; res = str.match(matcher); str = str.slice(pos)) { pos = res.index + res[0].length; if (res.groups) { ids.push(res.groups.id); } } return ids; } } function serializeEvent(original) { return Object .getOwnPropertyNames(Object.getPrototypeOf(original)) .reduce((serialized, field) => { switch (typeof original[field]) { case 'object': case 'symbol': case 'function': break; default: serialized[field] = original[field]; } serialized = { ...serialized, x: serialized.layerX, y: serialized.layerY }; return serialized; }, { type: original.type }); } export default class PointCloud extends React.Component { constructor(props) { super(props); this.videoRef = React.createRef(); this.peerConnected = false; } componentDidMount() { console.log(this.videoRef.current.width); this.socket = io("localhost:8080", { transports: ['websocket'], reconnection: true, query: { width: this.videoRef.current.width, height: this.videoRef.current.height } }); this.peer = new SimplePeer({ trickle: true, initiator: true, sdpTransform: (sdp) => { // Remove bandwidth restrictions // https://github.com/webrtc/samples/blob/89f17a83ed299ef28d45b933419d809b93d41759/src/content/peerconnection/bandwidth/js/main.js#L240 sdp = sdp.replace(/b=AS:.*\r\n/, '').replace(/b=TIAS:.*\r\n/, ''); // Force h264 encoding by removing all VP8/9 codecs from the sdp sdp = onlyH264(sdp); return sdp; } }); // Negotiate handshake this.socket.on('signal', (data) => this.peer.signal(data)); this.peer.on('signal', (data) => this.socket.emit('signal', data)); this.peer.on('stream', (stream) => { this.videoRef.current.srcObject = stream; }); this.peer.on('connect', () => { this.peerConnected = true; }); this.dispatchRemoteEvent(this.videoRef.current, 'blur'); this.dispatchRemoteEvent(this.videoRef.current, 'wheel'); this.dispatchRemoteEvent(this.videoRef.current, 'mouseup'); this.dispatchRemoteEvent(this.videoRef.current, 'mousemove'); this.dispatchRemoteEvent(this.videoRef.current, 'mousedown'); this.dispatchRemoteEvent(this.videoRef.current, 'mouseenter'); this.dispatchRemoteEvent(this.videoRef.current, 'mouseleave'); } dispatchRemoteEvent(target, type) { let timeout = null; target.addEventListener(type, (e) => { if (e.target === this.videoRef.current) { e.preventDefault(); } if (!timeout) { timeout = setTimeout(() => { timeout = null; }, 1000 / 60); if (this.peerConnected) { this.peer.send(JSON.stringify({ type: 'event', data: serializeEvent(e) })); } } }); } demoView() { return ( <div style={{ width: "2000px", height: "500px", display: "flex" }}> <video autoPlay muted width="1860px" height="500px" style={{ flexDirection: "row", float: "left" }} ref={this.videoRef} /> </div> ); } render() { return ( <DemoDashboard demoName={"Point Cloud Demo"} demoView={this.demoView()} onLoadClick={(fileName) => { console.log(fileName) }} onRenderClick={() => { console.log("Render Clicked") }} /> ) } }
0
rapidsai_public_repos/node/modules/demo/viz-app/pages
rapidsai_public_repos/node/modules/demo/viz-app/pages/demo/umap.jsx
// 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 { Tab, Tabs, TabList, TabPanel } from 'react-tabs'; import * as React from 'react'; import DemoDashboard from "../../components/demo-dashboard/demo-dashboard"; import HeaderUnderline from '../../components/demo-dashboard/header-underline/header-underline'; import ExtendedTable from '../../components/demo-dashboard/extended-table/extended-table'; import ToolBar from '../../components/demo-dashboard/tool-bar/tool-bar'; import FileInput from '../../components/demo-dashboard/file-input/file-input'; export default class UMAP extends React.Component { constructor(props) { super(props); this.dataTable = this.dataTable.bind(this); this.dataMetrics = this.dataMetrics.bind(this); } demoView() { return ( <p>Demo goes here.</p> ); } toolBar() { return ( <ToolBar onResetClick={() => { console.log("reset") }} onClearClick={() => { console.log("clear") }} onToolSelect={(tool) => { console.log(tool); }} /> ); } columns() { return [ { Header: 'Index', accessor: 'index', }, { Header: 'Col Name', accessor: 'colname1', }, { Header: 'Col Name', accessor: 'colname2', }, { Header: 'Col Name', accessor: 'colname3', }, { Header: 'Col Name', accessor: 'colname4', } ]; } fakeData(i) { return { index: `testvalue${i}`, colname1: `colname${i}`, colname2: `colname${i}`, colname3: `colname${i}`, colname4: `colname${i}`, colname2: `colname${i}`, colname3: `colname${i}`, colname4: `colname${i}`, }; } dataTable() { return ( <Tabs> <TabList> <Tab>Node List</Tab> <Tab>Edge List</Tab> </TabList> <TabPanel> <ExtendedTable cols={this.columns()} data={[ this.fakeData(0), this.fakeData(1), this.fakeData(2), this.fakeData(3), this.fakeData(4), this.fakeData(5), this.fakeData(6), this.fakeData(7), this.fakeData(8), this.fakeData(9), this.fakeData(10), this.fakeData(11), this.fakeData(12) ]} /> </TabPanel> <TabPanel> <div>This is edge list</div> </TabPanel> </Tabs> ) } dataMetrics() { return ( <div style={{ padding: 10, color: 'white' }}> <HeaderUnderline title={"Data Metrics"} fontSize={18} color={"white"}> <div>{'>'} 100,001,203 Edges</div> <div>{'>'} 20,001,525 Nodes</div> <div>{'>'} 5.2GB</div> </HeaderUnderline> <div style={{ height: 20 }} /> <HeaderUnderline title={"Query Log"} fontSize={18} color={"white"}> <FileInput useWhite={true} onChange={(path) => { console.log(path) }}> Export Selected ▼ </FileInput> </HeaderUnderline> </div> ) } render() { return ( <DemoDashboard demoName={"UMAP Demo"} demoView={this.demoView()} onLoadClick={(fileName) => { console.log(fileName) }} onRenderClick={() => { console.log("Render Clicked") }} dataTable={this.dataTable()} dataMetrics={this.dataMetrics()} isLoading={false} /> ) } }
0
rapidsai_public_repos/node/modules/demo/viz-app/pages
rapidsai_public_repos/node/modules/demo/viz-app/pages/demo/graph.jsx
// 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 { Tab, Tabs, TabList, TabPanel } from 'react-tabs'; import * as React from 'react'; import DemoDashboard from "../../components/demo-dashboard/demo-dashboard"; import HeaderUnderline from '../../components/demo-dashboard/header-underline/header-underline'; import ExtendedTable from '../../components/demo-dashboard/extended-table/extended-table'; import ToolBar from '../../components/demo-dashboard/tool-bar/tool-bar'; import { io } from "socket.io-client"; import SimplePeer from "simple-peer"; function onlyH264(sdp) { // remove non-h264 codecs from the supported codecs list const videos = sdp.match(/^m=video.*$/gm); if (videos) { return videos.map((video) => [video, [ ...getCodecIds(sdp, 'VP9'), ...getCodecIds(sdp, 'VP8'), ...getCodecIds(sdp, 'HEVC'), ...getCodecIds(sdp, 'H265') ]]).reduce((sdp, [video, ids]) => ids.reduce((sdp, id) => [ new RegExp(`^a=fmtp:${id}(.*?)$`, 'gm'), new RegExp(`^a=rtpmap:${id}(.*?)$`, 'gm'), new RegExp(`^a=rtcp-fb:${id}(.*?)$`, 'gm'), ].reduce((sdp, expr) => sdp.replace(expr, ''), sdp), sdp) .replace(video, ids.reduce((video, id) => video.replace(` ${id}`, ''), video)), sdp) .replace('\r\n', '\n').split('\n').map((x) => x.trim()).filter(Boolean).join('\r\n') + '\r\n'; } return sdp; function getCodecIds(sdp, codec) { return getIdsForMatcher(sdp, new RegExp( `^a=rtpmap:(?<id>\\d+)\\s+${codec}\\/\\d+$`, 'm' )).reduce((ids, id) => [ ...ids, id, ...getIdsForMatcher(sdp, new RegExp( `^a=fmtp:(?<id>\\d+)\\s+apt=${id}$`, 'm' )) ], []); } function getIdsForMatcher(sdp, matcher) { const ids = []; /** @type RegExpMatchArray */ let res, str = '' + sdp, pos = 0; for (; res = str.match(matcher); str = str.slice(pos)) { pos = res.index + res[0].length; if (res.groups) { ids.push(res.groups.id); } } return ids; } } function serializeEvent(original) { return Object .getOwnPropertyNames(Object.getPrototypeOf(original)) .reduce((serialized, field) => { switch (typeof original[field]) { case 'object': case 'symbol': case 'function': break; default: serialized[field] = original[field]; } serialized = { ...serialized, x: serialized.layerX, y: serialized.layerY }; return serialized; }, { type: original.type }); } export default class Graph extends React.Component { constructor(props) { super(props); this.dataTable = this.dataTable.bind(this); this.dataMetrics = this.dataMetrics.bind(this); this.videoRef = React.createRef(); this.peerConnected = false; this.state = { nodes: { tableData: [{}], tableColumns: [{ Header: "Loading...", accessor: "Loading..." }], length: 0 }, edges: { tableData: [{}], tableColumns: [{ Header: "Loading...", accessor: "Loading..." }], length: 0 } } } componentDidMount() { console.log(this.videoRef.current.width); this.socket = io("localhost:8080", { transports: ['websocket'], reconnection: true, query: { width: this.videoRef.current.width, height: this.videoRef.current.height } }); this.peer = new SimplePeer({ trickle: true, initiator: true, sdpTransform: (sdp) => { // Remove bandwidth restrictions // https://github.com/webrtc/samples/blob/89f17a83ed299ef28d45b933419d809b93d41759/src/content/peerconnection/bandwidth/js/main.js#L240 sdp = sdp.replace(/b=AS:.*\r\n/, '').replace(/b=TIAS:.*\r\n/, ''); // Force h264 encoding by removing all VP8/9 codecs from the sdp sdp = onlyH264(sdp); return sdp; } }); // Negotiate handshake this.socket.on('signal', (data) => this.peer.signal(data)); this.peer.on('signal', (data) => this.socket.emit('signal', data)); this.peer.on('stream', (stream) => { this.videoRef.current.srcObject = stream; }); this.peer.on('connect', () => { this.peerConnected = true; }); function processColumns(columnObject) { return Object.keys(columnObject).reduce( (prev, curr) => { return prev.concat([{ "Header": curr, "accessor": curr }]); }, []); } this.peer.on('data', (data) => { const decodedjson = JSON.parse(new TextDecoder().decode(data)); const keys = Object.keys(decodedjson.data); keys.forEach((key) => { if (['edges', 'nodes'].includes(key) && decodedjson.data[[key]].data.length > 0) { this.setState({ [key]: { tableColumns: processColumns(decodedjson.data[[key]].data[0]), tableData: decodedjson.data[[key]].data, length: decodedjson.data[[key]].length } }); } }); }); this.dispatchRemoteEvent(this.videoRef.current, 'blur'); this.dispatchRemoteEvent(this.videoRef.current, 'wheel'); this.dispatchRemoteEvent(this.videoRef.current, 'mouseup'); this.dispatchRemoteEvent(this.videoRef.current, 'mousemove'); this.dispatchRemoteEvent(this.videoRef.current, 'mousedown'); this.dispatchRemoteEvent(this.videoRef.current, 'mouseenter'); this.dispatchRemoteEvent(this.videoRef.current, 'mouseleave'); } dispatchRemoteEvent(target, type) { let timeout = null; target.addEventListener(type, (e) => { if (e.target === this.videoRef.current) { e.preventDefault(); } if (!timeout) { timeout = setTimeout(() => { timeout = null; }, 1000 / 60); if (this.peerConnected) { this.peer.send(JSON.stringify({ type: 'event', data: serializeEvent(e) })); } } }); } demoView() { return ( <div style={{ width: "2000px", height: "500px", display: "flex" }}> <video autoPlay muted width="1860px" height="500px" style={{ flexDirection: "row", float: "left" }} ref={this.videoRef} /** * Using synthetic react events is throwing: * `Unable to preventDefault inside passive event listener due to target being treated as passive`, * Temporarily using dom event listeners */ // onMouseUp={remoteEvent} // onMouseDown={remoteEvent} onMouseMove={remoteEvent} // onMouseLeave={remoteEvent} onWheel={remoteEvent} // onMouseEnter={remoteEvent} onBlur={remoteEvent} /> <ToolBar style={{ flexDirection: "row", width: "200px" }} onResetClick={() => { console.log("reset") }} onClearClick={() => { this.peer.send(JSON.stringify({ type: 'clearSelections', data: true })); }} onToolSelect={(tool) => { this.peer.send(JSON.stringify({ type: 'pickingMode', data: tool })); }} /> </div> ); } dataTable() { return ( <Tabs> <TabList> <Tab>Node List</Tab> <Tab>Edge List</Tab> </TabList> <TabPanel> <ExtendedTable cols={this.state.nodes.tableColumns} data={this.state.nodes.tableData} /> </TabPanel> <TabPanel> <ExtendedTable cols={this.state.edges.tableColumns} data={this.state.edges.tableData} /> </TabPanel> </Tabs> ) } dataMetrics() { return ( <div style={{ padding: 10, color: 'white' }}> <HeaderUnderline title={"Data Metrics"} fontSize={18} color={"white"}> <div>{'>'} {this.state.nodes.length} Edges</div> <div>{'>'} {this.state.edges.length} Nodes</div> </HeaderUnderline> </div> ) } render() { return ( <DemoDashboard demoName={"Graph Demo"} demoView={this.demoView()} onLoadClick={(fileName) => { console.log(fileName) }} onRenderClick={() => { console.log("Render Clicked") }} dataTable={this.dataTable()} dataMetrics={this.dataMetrics()} /> ) } }
0
rapidsai_public_repos/node/modules/demo
rapidsai_public_repos/node/modules/demo/spatial/package.json
{ "private": true, "name": "@rapidsai/demo-spatial", "main": "index.js", "version": "22.12.2", "license": "Apache-2.0", "author": "NVIDIA, Inc. (https://nvidia.com/)", "maintainers": [ "Paul Taylor <[email protected]>" ], "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", "@luma.gl/core": "8.5.16", "@rapidsai/cuda": "~22.12.2", "@rapidsai/cudf": "~22.12.2", "@rapidsai/cuspatial": "~22.12.2", "@rapidsai/glfw": "~22.12.2", "@rapidsai/jsdom": "~22.12.2", "mjolnir.js": "2.7.1", "react": "17.0.2", "react-dom": "17.0.2" }, "files": [ "app.jsx", "data.js", "util.js", "color.js", "index.js", "data/263_tracts.arrow", "package.json" ] }
0
rapidsai_public_repos/node/modules/demo
rapidsai_public_repos/node/modules/demo/spatial/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 = (glfwOptions = { title: 'Spatial 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
rapidsai_public_repos/node/modules/demo/spatial/data.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. const Path = require('path'); const https = require('https'); const {writeFile} = require('fs/promises'); const {finished} = require('stream/promises'); module.exports.loadSpatialDataset = loadSpatialDataset; if (require.main === module) { // loadSpatialDataset().catch((e) => console.error(e) || process.exit(1)); } async function loadSpatialDataset() { await writeFile(Path.join(__dirname, 'data', `168898952_points.arrow`), await loadFile()); } function loadFile() { const options = { method: `GET`, path: `/spatial/168898952_points.arrow.gz`, hostname: `node-rapids-data.s3.us-west-2.amazonaws.com`, headers: { [`Accept`]: `application/octet-stream`, [`Accept-Encoding`]: `br;q=1.0, gzip;q=0.8, deflate;q=0.6, identity;q=0.4, *;q=0.1`, }, }; return new Promise((resolve, reject) => { const req = https.request(options, (res) => { const encoding = res.headers['content-encoding'] || ''; let body = new Uint8Array(res.headers['content-length'] | 0); if (encoding.includes('gzip')) { res = res.pipe(require('zlib').createGunzip()); } else if (encoding.includes('deflate')) { res = res.pipe(require('zlib').createInflate()); } else if (encoding.includes('br')) { res = res.pipe(require('zlib').createBrotliDecompress()); } finished(res.on('data', (part) => { if (body.buffer.byteLength < body.byteOffset + part.byteLength) { const both = new Uint8Array(Math.max( body.buffer.byteLength * 2, body.buffer.byteLength + part.byteLength)); both.set(new Uint8Array(body.buffer, 0, body.byteOffset)); body = both.subarray(body.byteOffset); } body.set(part); body = body.subarray(part.byteLength); })) .then(() => { console.log(`Loaded "https://${[options.hostname, options.path].join('')}"`); resolve(new Uint8Array(body.buffer, 0, body.byteOffset)); }) .catch(reject); }); req.end(); finished(req).catch(reject); }); }
0
rapidsai_public_repos/node/modules/demo
rapidsai_public_repos/node/modules/demo/spatial/README.md
# Spatial Demo A geospatial demo using cuSpatial and deck.gl. ## Featured Dependencies - @rapidsai/cudf - @rapidsai/cuspatial - @rapidsai/jsdom - @rapidsai/deckgl - @rapidsai/glfw ## Data Requirements Data required from `/data/263_tracts.arrow` and census data (auto downloaded) such as `200901.cny.gz`. ## Start Example of starting demo: ```bash yarn start ```
0
rapidsai_public_repos/node/modules/demo
rapidsai_public_repos/node/modules/demo/spatial/util.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 { DataFrame, Float32, Int32, List, Series, Struct, Uint32, Uint8, } from '@rapidsai/cudf'; import {Quadtree} from '@rapidsai/cuspatial'; import {tableFromIPC} from 'apache-arrow'; import {existsSync} from 'fs'; import {readFile as fsReadFile} from 'fs/promises'; import * as Path from 'path'; import {loadSpatialDataset} from './data'; /** * @param {Map<number, [number, number, number, number]>} colorMap */ export async function loadPointsInCensusTracts(colorMap) { const {tracts, bbox, points, polyIds, levels} = await Promise.all([loadTracts(), loadPoints()]).then(([{tracts, bbox}, {quadtree}]) => ({ tracts, bbox, ...pointsInCensusTracts(tracts, quadtree), })); const colors = computeColors(tracts, points, colorMap); const pointsByLevel = filterPointsAndColorsByLevel(colors, levels, points, polyIds); const tract_polygons = copyPolygonsDtoH(tracts, colorMap); const tract_vertices = copyPolygonVerticesDtoH(tracts, colorMap); return { tracts, bbox, points, polyIds, levels, colors, pointsByLevel, tract_polygons, tract_vertices, }; } /** * @param {Map<number, [number, number, number, number]>} colorMap */ export async function loadPointsNearEachCensusTract(colorMap) { const {tracts, bbox, points, polyIds, levels} = await Promise.all([loadTracts(), loadPoints()]).then(([{tracts, bbox}, {quadtree}]) => ({ tracts, bbox, ...pointsNearCensusTracts(tracts, quadtree), })); const colors = computeColors(tracts, points, colorMap); const pointsByLevel = filterPointsAndColorsByLevel(colors, levels, points, polyIds); const tract_polygons = copyPolygonsDtoH(tracts, colorMap); const tract_vertices = copyPolygonVerticesDtoH(tracts, colorMap); return { tracts, bbox, points, polyIds, levels, colors, pointsByLevel, tract_polygons, tract_vertices, }; } export async function loadTracts() { console.time(`load geometry Arrow table (${(263).toLocaleString()} polys)`); const table = tableFromIPC(await fsReadFile(Path.join(__dirname, 'data', '263_tracts.arrow'))); console.timeEnd(`load geometry Arrow table (${(263).toLocaleString()} polys)`); console.time(`copy census tracts to GPU and compute bbox (${(263).toLocaleString()} polys)`); /** * @type DataFrame<{ id: Int32, polygon: List<List<Struct<{x: Float32, y: Float32}>>> }> */ const tracts = new DataFrame({ id: Series.new(table.getChildAt(0)), polygon: Series.new(table.getChildAt(1)), }); const [xMin, xMax] = tracts.get('polygon').elements.elements.getChild('x').minmax(); const [yMin, yMax] = tracts.get('polygon').elements.elements.getChild('y').minmax(); console.timeEnd(`copy census tracts to GPU and compute bbox (${(263).toLocaleString()} polys)`); return { tracts, bbox: { xMin, xMax, yMin, yMax, width: xMax - xMin, height: yMax - yMin, } }; } export async function loadPoints() { const table = await loadPointsTable(); console.time(`copy points to GPU (${(168898952).toLocaleString()} points)`); /** * @type DataFrame<{ x: Float32, y: Float32 }> */ const points = new DataFrame({ x: Series.new(table.getChildAt(0)), y: Series.new(table.getChildAt(1)), }); console.timeEnd(`copy points to GPU (${(168898952).toLocaleString()} points)`); return {points, ...createQuadtree(points)}; async function loadPointsTable(loadDatasetIfNotFound = true) { try { console.time(`load points Arrow table (${(168898952).toLocaleString()} points)`); const filePath = Path.join(__dirname, 'data', '168898952_points.arrow'); if (!existsSync(filePath)) { throw new Error(`file not found: "${filePath}"`); } const table = tableFromIPC(await fsReadFile(filePath)); console.timeEnd(`load points Arrow table (${(168898952).toLocaleString()} points)`); return table; } catch (e) { if (loadDatasetIfNotFound) { console.log('Point data not found, downloading now...'); return await loadSpatialDataset().then(() => loadPointsTable(false)) } console.error(` Point data not found! Run this to download the sample data from AWS S3 (1.3GiB): node ${Path.join(__dirname, 'data.js')} `); process.exit(1); } } } /** * * @param {DataFrame<{ x: Float32; y: Float32; }>} points * @returns */ export function createQuadtree(points) { console.time(`construct quadtree for ${points.numRows.toLocaleString()} points`); const [xMin, xMax] = points.get('x').minmax(); const [yMin, yMax] = points.get('y').minmax(); const [width, height] = [xMax - xMin, yMax - yMin]; const scale = Math.min(width / window.outerWidth, height / window.outerHeight); const minSize = Math.sqrt(points.numRows); const quadtree = Quadtree.new({ x: points.get('x'), y: points.get('y'), xMin, xMax, yMin, yMax, maxDepth: 15, scale, minSize, }); console.timeEnd(`construct quadtree for ${points.numRows.toLocaleString()} points`); return { quadtree, bbox: { xMin, xMax, yMin, yMax, width: xMax - xMin, height: yMax - yMin, } }; } /** * @param {DataFrame<{ id: Int32, polygon: List<List<Struct<{x: Float32, y: Float32}>>> }>} tracts * @param {Quadtree<Float32>} quadtree */ export function pointsInCensusTracts(tracts, quadtree) { // Filter points by which census tract they're in console.time(`query for points in census tract polygons (${ quadtree.keyMap.length.toLocaleString()} points, ${tracts.numRows.toLocaleString()} polygons)`); const polyAndPointIdxs = quadtree.pointInPolygon(tracts.get('polygon')); const polyIds = polyAndPointIdxs.get('polygon_index'); console.timeEnd(`query for points in census tract polygons (${ quadtree.keyMap.length.toLocaleString()} points, ${tracts.numRows.toLocaleString()} polygons)`); console.time(`gather query result points (${polyIds.length.toLocaleString()} points)`); const filteredPoints = quadtree.points.gather(polyAndPointIdxs.get('point_index')); const filteredLevels = quadtree.level.gather(polyIds); console.timeEnd(`gather query result points (${polyIds.length.toLocaleString()} points)`); return {points: filteredPoints, levels: filteredLevels, polyIds, tracts, quadtree}; } /** * @param {DataFrame<{ id: Int32, polygon: List<List<Struct<{x: Float32, y: Float32}>>> }>} tracts * @param {Quadtree<Float32>} quadtree */ export function pointsNearCensusTracts(tracts, quadtree) { // Filter points by which census tract they're in console.time(`query for points nearest to each census tract boundary (${ quadtree.keyMap.length.toLocaleString()} points, ${tracts.numRows.toLocaleString()} polygons)`); const polyAndPointIdxs = quadtree.pointToNearestPolyline(tracts.get('polygon').elements, 1); const polyIds = polyAndPointIdxs.get('polyline_index'); console.timeEnd(`query for points nearest to each census tract boundary (${ quadtree.keyMap.length.toLocaleString()} points, ${tracts.numRows.toLocaleString()} polygons)`); console.time(`gather query result points (${polyIds.length.toLocaleString()} points)`); const filteredPoints = quadtree.points.gather(polyAndPointIdxs.get('point_index')); const filteredLevels = quadtree.level.gather(polyIds); console.timeEnd(`gather query result points (${polyIds.length.toLocaleString()} points)`); return {points: filteredPoints, levels: filteredLevels, polyIds, tracts, quadtree}; } /** * @param {DataFrame<{ id: Int32, polygon: List<List<Struct<{x: Float32, y: Float32}>>> }>} tracts * @param {DataFrame<{ x: Float32; y: Float32; }>} points * @param {Map<number, [number, number, number, number]>} colorMap */ export function computeColors(tracts, points, colorMap) { console.time(`compute colors (${points.numRows.toLocaleString()} points)`); const colors = (() => { const swizzle = ([r, g, b, a]) => [b, g, r, a]; const idxs = Array.from({length: tracts.numRows}, (_, i) => i); const palette = idxs.map((i) => swizzle(colorMap.get(i))).flat(); return Series.new(new Uint8Array(palette)).view(new Uint32); })(); console.timeEnd(`compute colors (${points.numRows.toLocaleString()} points)`); return colors; } /** * * @param {Series<Uint32>} colors * @param {Series<Uint8>} levels * @param {DataFrame<{x:Float32, y:Float32}>} points * @param {Series<Uint32>} polyIds * @returns */ export function filterPointsAndColorsByLevel(colors, levels, points, polyIds) { const [minLevel, maxLevel] = levels.minmax().map(Number); // console.log({minLevel, maxLevel}); console.time(`filter points and colors by level (${points.numRows.toLocaleString()} points)`); const pointsByLevel = Array.from({length: (maxLevel - minLevel) + 1}, (_, i) => { const mask = levels.eq(minLevel + i); const lvlIds = polyIds.filter(mask); const lvlPoints = points.filter(mask); const lvlColors = colors.gather(lvlIds); return { level: minLevel + i, numNodes: mask.sum(), data: getPointsInBatches(lvlPoints, lvlColors, lvlIds) }; }); console.timeEnd(`filter points and colors by level (${points.numRows.toLocaleString()} points)`); return pointsByLevel; } /** * @param {DataFrame<{ id: Int32, polygon: List<List<Struct<{x: Float32, y: Float32}>>> }>} tracts * @param {Map<number, [number, number, number, number]>} colorMap */ export function copyPolygonsDtoH(tracts, colorMap) { console.time(`copy census tracts DtoH (${tracts.numRows.toLocaleString()} tracts)`); const result = [...tracts.toArrow()].map(({id, polygon}) => { return { id, color: colorMap.get(id), rings: [...polygon].map((ring) => [...ring].map(({x, y}) => [x, y])), }; }); console.timeEnd(`copy census tracts DtoH (${tracts.numRows.toLocaleString()} tracts)`); return result; } /** * @param {DataFrame<{ id: Int32, polygon: List<List<Struct<{x: Float32, y: Float32}>>> }>} tracts * @param {Map<number, [number, number, number, number]>} colorMap */ export function copyPolygonVerticesDtoH(tracts, colorMap) { console.time(`copy census tract vertices DtoH (${tracts.numRows.toLocaleString()} tracts)`); const result = [...tracts.toArrow()].flatMap(({id, polygon}) => { const color = colorMap.get(id); return [...polygon].flatMap((ring) => [...ring].map(({x, y}) => ({ id, color, position: [x, y, 0], radius: Math.max(3, 2 + (id % 7)), strokeWidth: Math.max(1, (id % 3)), }))); }); console.timeEnd(`copy census tract vertices DtoH (${tracts.numRows.toLocaleString()} tracts)`); return result; } const sleep = (t) => new Promise((r) => setTimeout(r, t)); /** * * @param {DataFrame<{ x: Float32; y: Float32; }>} points * @param {Series<Uint32>} polyIds * @returns */ export function getPointsInBatches(points, colors, polyIds) { return { async * [Symbol.asyncIterator]() { const count = Math.ceil(points.numRows / 1e6); const length = Math.floor(points.numRows / count); for (let offset = 0; offset < (count * length); offset += length) { yield { length, offset, attributes: { nodeFillColors: colors.data.subarray(offset, offset + length), nodeElementIndices: polyIds.data.subarray(offset, offset + length), nodeXPositions: points.get('x').data.subarray(offset, offset + length), nodeYPositions: points.get('y').data.subarray(offset, offset + length), nodeRadius: Series.sequence({type: new Uint8, init: 5, size: length, step: 0}).data, } }; await sleep(16); } } }; }
0
rapidsai_public_repos/node/modules/demo
rapidsai_public_repos/node/modules/demo/spatial/color.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. const goldenRatioConjugate = 0.618033988749895; export class ColorMapper { constructor(hue = 0.99, saturation = 0.99, brightness = 0.99) { this._h = hue % 1; this._s = saturation % 1; this._v = brightness % 1; this._map = Object.create(null); } get(id) { return this._map[id] || (this._map[id] = this.generate()); } generate() { const rgba = HSVtoRGBA(this._h, this._s, this._v); this._h = (this._h + goldenRatioConjugate) % 1; return rgba; } } // # HSV values in [0..1] // # returns [r, g, b] values from 0 to 255 function HSVtoRGBA(h, s, v) { var r, g, b, i, f, p, q, t; if (arguments.length === 1) { s = h.s, v = h.v, h = h.h; } i = Math.floor(h * 6); f = h * 6 - i; p = v * (1 - s); q = v * (1 - f * s); t = v * (1 - (1 - f) * s); switch (i % 6) { case 0: r = v, g = t, b = p; break; case 1: r = q, g = v, b = p; break; case 2: r = p, g = v, b = t; break; case 3: r = p, g = q, b = v; break; case 4: r = t, g = p, b = v; break; case 5: r = v, g = p, b = q; break; } return [ Math.round(r * 255), // r Math.round(g * 255), // g Math.round(b * 255), // b 255, // a ] }
0
rapidsai_public_repos/node/modules/demo
rapidsai_public_repos/node/modules/demo/spatial/app.jsx
// 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 { Series } from '@rapidsai/cudf'; import { GraphLayer } from '@rapidsai/deck.gl'; // Preload cuDF kernels into device memory Series.new([0, 1, 2]).sum(); import * as React from 'react'; import DeckGL from '@deck.gl/react'; import { log as deckLog, OrthographicView } from '@deck.gl/core'; deckLog.level = 0; deckLog.enable(false); import { PolygonLayer, ScatterplotLayer, TextLayer } from '@deck.gl/layers'; import { ColorMapper } from './color'; import { loadPointsInCensusTracts, // loadPointsNearEachCensusTract, } from './util'; export default class App extends React.Component { constructor(...args) { super(...args); this.state = { pointsByLevel: [], tract_polygons: [], tract_vertices: [], }; this._deck = React.createRef(); this._onViewStateChanged = this._onViewStateChanged.bind(this); loadPointsInCensusTracts(new ColorMapper()) // loadPointsNearEachCensusTract(new ColorMapper()) .then(({ bbox, pointsByLevel, tract_polygons, tract_vertices }) => { const { width, height } = bbox; const zoom = (() => { const outerWidth = window.outerWidth * .75; const outerHeight = window.outerHeight * .75; const world = (width > height ? width : height); const screen = (width > height ? outerWidth : outerHeight); const zoom = (world > screen ? -(world / screen) : (screen / world)) * 1.1; return Math.log2(Math.abs(zoom)) * Math.sign(zoom); })(); this.setState({ bbox, selectedLevels: [], highlightedLevel: undefined, rerender: true, pointsByLevel, tract_polygons, tract_vertices, viewState: { zoom, width: window.outerWidth, height: window.outerHeight, minZoom: Number.NEGATIVE_INFINITY, maxZoom: Number.POSITIVE_INFINITY, target: [ bbox.xMin + width * 0.5, bbox.yMin + height * 0.5, 0 ], } }); }); } _onViewStateChanged({ viewState, oldViewState }) { this.setState({ viewState, rerender: viewState.zoom !== oldViewState.zoom, }); } render() { let { xMin, yMin } = this.state.bbox || {}; const [viewport] = this._deck?.current?.deck?.viewManager?.getViewports() || []; if (viewport) { const { target, width, height } = this.state.viewState; const [xMid, yMid] = viewport.project(target); [xMin, yMin] = viewport.unproject([ xMid - (width * 0.5), yMid - (height * 0.5) ]); } const visibleLevels = [].concat(this.state.highlightedLevel ?? [], this.state.selectedLevels); return ( <DeckGL ref={this._deck} viewState={this.state.viewState || {}} onViewStateChange={this._onViewStateChanged} controller={{ keyboard: false, doubleClickZoom: false }} onAfterRender={() => this.state.rerender && this.setState({ rerender: false })} onClick={() => this.setState({ selectedLevels: [], highlightedLevel: undefined })} views={[new OrthographicView({ clear: { color: [...[46, 46, 46].map((x) => x / 255), 1] } })]} > <PolygonLayer id='tract_polygons' opacity={0.5} filled={true} stroked={true} extruded={false} positionFormat={`XY`} lineWidthMinPixels={1} data={this.state.tract_polygons || []} getPolygon={({ rings }) => rings} getElevation={({ id }) => id} getFillColor={({ color }) => [...color.slice(0, 3), 15]} getLineColor={({ color }) => [...color.slice(0, 3), 255]} /> <ScatterplotLayer id='tract_vertices' opacity={0.05} filled={false} stroked={true} radiusMinPixels={2} data={this.state.tract_vertices || []} getRadius={(x) => x.radius} getLineColor={(x) => x.color} getPosition={(x) => x.position} getLineWidth={(x) => x.strokeWidth} /> <React.Fragment> { this.state.pointsByLevel .filter(({ level }) => visibleLevels.indexOf(level) !== -1) .map(({ numNodes, data, level }) => ( <GraphLayer id={`points_by_level_${level}`} autoHighlight={false} pickable={false} data={data} dataTransform={(nodes) => ({ edges: {}, nodes })} numNodes={numNodes} numEdges={0} nodesVisible={true} edgesVisible={false} nodesFilled={true} nodesStroked={false} nodeRadiusScale={10} nodeRadiusMinPixels={0} nodeRadiusMaxPixels={1} /> )) } </React.Fragment> <TextLayer data={this.state.pointsByLevel.map(({ level }) => ({ level, size: 15, text: `Level ${level}`, position: [xMin, yMin], color: [255, 255, 255], }))} opacity={1.0} sizeScale={1} maxWidth={2000} pickable={true} background={true} getTextAnchor={'start'} getAlignmentBaseline={'top'} getSize={({ size }) => size} getColor={({ color, level }) => [...color, visibleLevels.indexOf(level) !== -1 ? 255 : 150]} getPosition={({ position }) => position} getPixelOffset={({ level }) => [0, level * 15]} getBackgroundColor={() => [46, 46, 46]} onHover={(info) => { this.setState({ highlightedLevel: info?.object?.level }); return true; }} onClick={(info, event) => { const level = info?.object?.level; if (typeof level === 'number') { const { shiftKey = false } = (event.pointers && event.pointers[0] || {}); if (this.state.selectedLevels.indexOf(level) === -1) { this.setState({ highlightedLevel: undefined, selectedLevels: shiftKey ? this.state.selectedLevels.concat(level) : [level], }); } else { this.setState({ highlightedLevel: shiftKey ? undefined : this.state.highlightedLevel, selectedLevels: shiftKey ? this.state.selectedLevels.filter((l) => l !== level) : [level], }); } } return true; }} /> </DeckGL> ); } }
0
rapidsai_public_repos/node/modules/demo/spatial
rapidsai_public_repos/node/modules/demo/spatial/data/263_tracts.arrow
version https://git-lfs.github.com/spec/v1 oid sha256:49827aedaa036f9fb16cebd838bcbaa4752824f13fa5c9dac0f6c994e32a2c73 size 718232
0
rapidsai_public_repos/node/modules/demo
rapidsai_public_repos/node/modules/demo/xterm/package.json
{ "private": true, "name": "@rapidsai/demo-xterm", "main": "index.js", "version": "22.12.2", "license": "Apache-2.0", "author": "NVIDIA, Inc. (https://nvidia.com/)", "maintainers": [ "Paul Taylor <[email protected]>" ], "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", "xterm": "4.3.0", "xterm-addon-webgl": "0.4.1" }, "files": [ "index.js", "package.json" ] }
0
rapidsai_public_repos/node/modules/demo
rapidsai_public_repos/node/modules/demo/xterm/index.js
#!/usr/bin/env node // 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. module.exports = (glfwOptions = { title: 'XTerm Demo' }) => { const jsdom = new (require('@rapidsai/jsdom').RapidsJSDOM)({glfwOptions}); jsdom.window.evalFn(() => { const {Terminal} = require('xterm'); const {WebglAddon} = require('xterm-addon-webgl'); // Create xterm.js terminal const terminal = new Terminal(); terminal.open(document.body); // Hack to override font size measurement hackFontMeasurement(terminal); // load xterm.js WebGL renderer terminal.loadAddon(new WebglAddon()); // handle keyboard input terminal.onKey(handleKeyInput); // print initial startup message printStartupMessage(terminal); function hackFontMeasurement(terminal) { Object.defineProperty( terminal._core._charSizeService._measureStrategy._measureElement, 'getBoundingClientRect', { value() { return { width: 9, height: 14 } } }); terminal._core._charSizeService.measure(); window._inputEventTarget = terminal.textarea; window.requestAnimationFrame(function af() { window.requestAnimationFrame(af); }); return terminal; } function handleKeyInput(e) { const ev = e.domEvent; const printable = !ev.altKey && !ev.ctrlKey && !ev.metaKey; if (e.key !== ' ' && ev.type !== 'keydown') return; if (ev.keyCode === 13) { terminal.prompt(); } else if (ev.keyCode === 8) { // Do not delete the prompt if (terminal._core.buffer.x > 2) { terminal.write('\b \b'); } } else if (printable) { terminal.write(e.key); } } function printStartupMessage(terminal) { terminal.prompt = () => { terminal.write('\r\n$ '); }; terminal.writeln('Welcome to xterm.js'); terminal.writeln( 'This is a local terminal emulation, without a real terminal in the back-end.'); terminal.writeln('Type some keys and commands to play around.'); terminal.writeln(''); terminal.prompt(); return terminal; } }); return jsdom; }; if (require.main === module) { module.exports().window.addEventListener('close', () => process.exit(0), {once: true}); }
0
rapidsai_public_repos/node/modules/demo
rapidsai_public_repos/node/modules/demo/xterm/README.md
## XTerm Demo Running a GL powered Xterm in a glfw instance. Uses the [Xterm.js project](https://github.com/xtermjs/xterm.js). ## Featured Dependencies - @rapidsai/glfw ## Start Example of running the demo: ```bash yarn start ```
0
rapidsai_public_repos/node/modules/demo
rapidsai_public_repos/node/modules/demo/client-server/package.json
{ "name": "@rapidsai/demo-client-server", "version": "22.12.2", "private": true, "author": "NVIDIA, Inc. (https://nvidia.com/)", "maintainers": [ "Ajay Thorve([email protected])" ], "bin": "index.js", "scripts": { "dev": "next dev", "build": "next build", "start": "next build && next start" }, "dependencies": { "@deck.gl/carto": "8.8.10", "@deck.gl/core": "8.8.10", "@deck.gl/geo-layers": "8.8.10", "@deck.gl/layers": "8.8.10", "@deck.gl/mesh-layers": "8.8.10", "@deck.gl/react": "8.8.10", "@fortawesome/fontawesome-svg-core": "1.2.35", "@fortawesome/free-solid-svg-icons": "5.15.3", "@fortawesome/react-fontawesome": "0.1.14", "apache-arrow": "^9.0.0", "bootstrap": "4.6.0", "d3": "6.6.2", "echarts": "5.0.2", "echarts-for-react": "3.0.1", "maplibre-gl": "2.4.0", "mjolnir.js": "2.7.1", "next": "11.1.3", "react": "17.0.2", "react-bootstrap": "1.6.1", "react-dom": "17.0.2", "react-map-gl": "7.0.19" }, "devDependencies": { "@babel/core": "7.15.5" }, "files": [ "pages", "styles", "public/images", "public/data/SOURCES.md", "components", "next.config.js", "package.json" ] }
0
rapidsai_public_repos/node/modules/demo
rapidsai_public_repos/node/modules/demo/client-server/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. const Path = require('path'); // Change cwd to the example dir so relative file paths are resolved process.chdir(__dirname); const next = require.resolve('next/dist/bin/next'); require('fs').stat(Path.join(__dirname, '.next'), (err, stats) => { const {spawnSync} = require('child_process'); const env = { NEXT_TELEMETRY_DISABLED: 1, // disable https://nextjs.org/telemetry ...process.env, }; if (err || !stats || !stats.isDirectory()) { spawnSync(process.execPath, [next, 'build'], {env, cwd: __dirname, stdio: 'inherit'}); } spawnSync(process.execPath, [next, 'start'], {env, cwd: __dirname, stdio: 'inherit'}); });
0
rapidsai_public_repos/node/modules/demo
rapidsai_public_repos/node/modules/demo/client-server/README.md
# Client-Server Visualization Demo This demo showcases how to use cudf as a backend compute engine for a client-side deck.gl visualization over a node-express api using 2 dashboards - Uber Movement Dataset Dashboard and Fannie Mae Mortgage Dataset Dashboard. ### Uber Movement Dashboard ![Screenshot](./public/images/uber.png) ### Mortgage Dashboard ![Screenshot](./public/images/mortgage.png) ## Featured Dependencies - @rapidsai/cudf - deckgl - apache-arrow ## Data Requirements ### Uber Movement Dataset The data needs to be downloaded from [Uber Movements](https://movement.uber.com/explore/san_francisco/travel-times) with the following sequence of actions: - `Click 'Download data' > Click 'All data' > Slect '2020 Quarter' > Download 'Travel Times By Date By Hour Buckets (All Days).csv'`(1.7gb) - Save the file as `san_fran_uber.csv` in the folder `/public/data` - If not already included, also download the `san_francisco_censustracts.geojson`(3.8mb) file into `/public/data`. NOTE: you may have to rename from a .json to .geojson extension. ### Mortgage Dataset - The data needs to be [downloaded here](https://drive.google.com/u/0/uc?id=1KZBzbw9z-BkyuxfN4HB0u_vKbpaEjDTm&export=download&confirm=t) (4.5gb). - Save the file as `mortgage.csv` in the folder `/public/data` ## Start Start with the command below, then open `http://localhost:3000` ```bash yarn start ```
0
rapidsai_public_repos/node/modules/demo
rapidsai_public_repos/node/modules/demo/client-server/next.config.js
module.exports = { eslint: { ignoreDuringBuilds: true, }, webpack: (config, {buildId, dev, isServer, defaultLoaders, webpack}) => { // Note: we provide webpack above so you should not `require` it // Perform customizations to webpack config // config.plugins.push(new webpack.IgnorePlugin({ resourceRegExp: /.*?\.node/ig })) config.externals.push({'mapbox-gl': 'maplibre-gl'}); if (isServer) { config.externals.push({ '@rapidsai/core': '@rapidsai/core', '@rapidsai/cuda': '@rapidsai/cuda', '@rapidsai/webgl': '@rapidsai/webgl', '@rapidsai/deck.gl': '@rapidsai/deck.gl', '@rapidsai/rmm': '@rapidsai/rmm', '@rapidsai/glfw': '@rapidsai/glfw', '@rapidsai/cudf': '@rapidsai/cudf', '@rapidsai/cugraph': '@rapidsai/cugraph', '@rapidsai/cuspatial': '@rapidsai/cuspatial', 'apache-arrow': 'apache-arrow' }); } // console.log(require('util').inspect({ isServer, config }, false, Infinity, true)); // Important: return the modified config return config; }, }
0
rapidsai_public_repos/node/modules/demo/client-server
rapidsai_public_repos/node/modules/demo/client-server/styles/global.css
/* 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. */ body { width: 100vw; height: 100vh; margin: 0; overflow: hidden; background-color: #212121!important } .container-fluid { height: 80%; } .row, .card { height: 100%; } .card-body { position: relative; background-color: #212121!important } .legend{ background-color: #212121; opacity: 0.8; } .card-header { padding: 0.6rem 1rem !important; } .container-fluid .row .col{ margin: 2px 0px !important; padding: 0px 1px; } .deck-tooltip { font-family: Helvetica, Arial, sans-serif; padding: 6px !important; margin: 8px; max-width: 300px; background-color: rgb(33 33 33); color: white; font-size: 10px; }
0
rapidsai_public_repos/node/modules/demo/client-server
rapidsai_public_repos/node/modules/demo/client-server/components/navbar.module.css
/* 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. */ .logo{ border-radius: 5%; } .navbar{ background-color: #7300ff!important; padding:0% 0.5% !important; }
0
rapidsai_public_repos/node/modules/demo/client-server
rapidsai_public_repos/node/modules/demo/client-server/components/layout.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 styles from './layout.module.css' import CustomNavbar from './navbar' export default function Layout({ title, children, resetall, displayReset }) { return ( <> <CustomNavbar title={title} resetall={resetall} displayReset={displayReset}></CustomNavbar> <div className={styles.container}> {children} </div> </> ) }
0
rapidsai_public_repos/node/modules/demo/client-server
rapidsai_public_repos/node/modules/demo/client-server/components/layout.module.css
/* 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. */ .container { width: 100%; height: 80%; padding: 0 1rem; margin: 1rem auto 3rem; }
0
rapidsai_public_repos/node/modules/demo/client-server
rapidsai_public_repos/node/modules/demo/client-server/components/navbar.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 Navbar from 'react-bootstrap/Navbar'; import Button from 'react-bootstrap/Button'; import Nav from 'react-bootstrap/Nav'; import Image from 'next/image'; import 'bootstrap/dist/css/bootstrap.min.css'; import styles from './navbar.module.css'; import Link from 'next/link' export default function CustomNavbar({ title, resetall, displayReset }) { return ( <Navbar bg="dark" variant="dark" className={styles.navbar}> <Link href="/"> <a><Image src="/images/rapids.png" className={styles.logo} width={80} height={40} border-radius={10} ></Image></a> </Link> <Navbar.Brand href="#"> <h2>{title}</h2></Navbar.Brand> <Nav className="mr-auto"></Nav> <div> {displayReset != "false" && <Button variant="primary" onClick={resetall}>Reset all</Button> } </div> </Navbar > ) }
0
rapidsai_public_repos/node/modules/demo/client-server/components
rapidsai_public_repos/node/modules/demo/client-server/components/utils/legend.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 * as d3 from "d3"; export function generateLegend(container, keys, thresholdScale) { // select the svg area var svg = d3.select(container) // Add one dot in the legend for each name. var size = 20 svg.selectAll('mydots') .data(Object.keys(keys)) .enter() .append('rect') .attr('x', 10) .attr('y', function (d, i) { return 10 + i * (size + 5) }) // 100 is where the first dot appears. // 25 is the distance between dots .attr('width', size) .attr('height', size) .style('fill', function (d) { const values = thresholdScale(d); return 'rgb(' + values.join(', ') + ')'; }) .style('opacity', 0.8) // Add one dot in the legend for each name. svg.selectAll('mylabels') .data(Object.keys(keys)) .enter() .append('text') .attr('x', 10 + size * 1.2) .attr('y', function (d, i) { return 10 + i * (size + 5) + (size / 2) }) // 100 is where the first dot appears. 25 is the distance between dots .style('fill', function (d) { const values = thresholdScale(d); return 'rgb(' + values.join(', ') + ')'; }) .text(function (d) { return keys[d] }) .attr('text-anchor', 'left') .style('alignment-baseline', 'middle') .style('opacity', 0.8) }
0
rapidsai_public_repos/node/modules/demo/client-server/components
rapidsai_public_repos/node/modules/demo/client-server/components/charts/deck.geo.jsx
// 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. import { BASEMAP } from '@deck.gl/carto'; import { GeoJsonLayer } from '@deck.gl/layers'; import DeckGL from '@deck.gl/react'; import { tableFromIPC } from 'apache-arrow'; import * as React from 'react'; import { Button, Card } from 'react-bootstrap'; import { Map } from 'react-map-gl'; import { generateLegend } from '../../components/utils/legend'; export default class CustomChoropleth extends React.Component { constructor(props) { super(props); this.state = { gjson: [], data: [], clicked: false, current_query: this.props.getquery() }; this._onHover = this._onHover.bind(this); this._onClick = this._onClick.bind(this); this._renderTooltip = this._renderTooltip.bind(this); this._getFillColor = this._getFillColor.bind(this); this._reset = this._reset.bind(this); } _fillColor() { if (!this.props.fillcolor) { return this.props.columns[0] } return this.props.fillcolor; } _elevation() { if (!this.props.elevation) { return this.props.columns[0] } return this.props.elevation; } componentDidMount() { const { geojsonurl = undefined } = this.props; if (geojsonurl) { fetch(geojsonurl) .then(response => response.json()) .then(({ features }) => { this.setState({ gjson: features }); }) .then(() => this._updateLayerData()) .then((data) => this.setState({ data: data })) .catch((e) => console.log(e)); } generateLegend( '#' + this.props.by + 'legend', this.props.legend_props, this.props.thresholdScale); } componentDidUpdate() { // if parent componet `getquery()` is updated, and is not the same as state.current_query, // refetch the data with current query if (this.props.getquery() !== this.state.current_query) { let updateState = { current_query: this.props.getquery() } if (!this.props.getquery().hasOwnProperty(this.props.by)) { // if current chart selections have also been reset updateState['clicked'] = false; } // update state this.setState(updateState); // update data this._updateLayerData() .then((data) => this.setState({ data: data })) .catch((e) => console.log(e)); } } _generateApiUrl() { const { dataset = undefined, by = undefined, agg = undefined, columns = undefined // return all columns } = this.props; if (!dataset || !by || !agg) { return null; } const query = JSON.stringify(this.props.getquery()); return `http://localhost:3000/api/${dataset}/groupby/${by}/${agg}?columns=${columns}&query_dict=${query}`; } /** * transform Arrow.Table to the format * {index[0]: {property: propertyValue, ....}, * index[1]: {property: propertyValue, ....}, * ...} for easier conversion to geoJSON object * * @param data Arrow.Table * @param by str, column name * @param params [{}, {}] result of Arrow.Table.toArray() * @returns {index:{props:propsValue}} */ _transformData(data, by, params) { return data.reduce((a, v) => { a[v[by]] = params.reduce((res, x) => { res[x] = v[x]; return res }, {}); return a; }, {}); } /** * TODO: pass arrow to binary input to GeoJSONLayer instead of geojson * convert an Arrow table to a geoJSON to be consumed by DeckGL GeoJSONLayer. Arrow table results * from cudf.DataFrame.toArrow() function. * * @param table Arrow.Table * @param by str, column name to be matched to the geoJSONProperty in the gjson object * @param properties [] of column names, properties to add from data to result geoJSON * @param geojsonProp str, property name in gjson object to be mapped to `by` * @returns geoJSON object consumable by DeckGL GeoJSONLayer */ _convertToGeoJSON(table, by, properties, geojsonProp) { const data = this._transformData(table.toArray(), by, properties); let tempjson = []; this.state.gjson.forEach((val) => { if (val.properties[geojsonProp] in data) { tempjson.push({ type: val.type, geometry: val.geometry, properties: { ...val.properties, ...data[val.properties[geojsonProp]] } }) } }); return tempjson; } async _updateLayerData() { const url = this._generateApiUrl(); // `/uber/tracts/groupby/sourceid/mean?columns=travel_time`; if (!url) { return null; } const table = await tableFromIPC(fetch(url, { method: 'GET' })); return this._convertToGeoJSON(table, this.props.by, this.props.columns, this.props.geojsonprop); } _getFillColor(f) { const x = f?.properties[this._fillColor()]; const id = f?.properties[this.props.geojsonprop]; if (x !== undefined && id !== undefined) { if (this.state.clicked !== false) { if (this.state.clicked !== parseInt(id)) { return ([255, 255, 255, 10]); } else { return this.props.thresholdScale(x); } } else { return this.props.thresholdScale(x); } } } _onHover({ x, y, object }) { this.setState({ x, y, hoveredRegion: object }); } _renderTooltip() { const { x, y, hoveredRegion } = this.state; return ( hoveredRegion && ( <div className='deck-tooltip' style={{ position: 'absolute', left: x, top: y }}> { Object.keys(hoveredRegion.properties).map((value, idx) => { return ` ${value}: ${hoveredRegion.properties[[value]]} `; }) } {/* {hoveredRegion.properties.DISPLAY_NAME} <br /> Mean Travel Time: {hoveredRegion.properties.travel_time} */} </div >) ); } _onClick(f) { const id = f?.object?.properties[this.props.geojsonprop]; if (this.state.clicked !== parseInt(id)) { this.props.updatequery({ [this.props.by]: parseInt(id) }); this.setState({ clicked: parseInt(id) }); } else { //double click deselects this._reset(); } } _renderLayers() { const { data } = this.state; return [new GeoJsonLayer({ data, highlightColor: [200, 200, 200, 200], autoHighlight: true, wireframe: false, pickable: true, stroked: false, // only on extrude false filled: true, extruded: true, lineWidthScale: 10, // only if extrude false lineWidthMinPixels: 1, getPointRadius: 100, // only if points getLineWidth: 10, opacity: 50, getFillColor: this._getFillColor, getElevation: f => f?.properties[this._elevation()] * 5, onClick: this._onClick, onHover: this._onHover, getLineColor: [0, 188, 212, 100], updateTriggers: { getFillColor: [this.state.clicked, this.state.data], getElevation: [this.state.data] } })] } _reset() { this.props.updatequery({ [this.props.by]: undefined }); this.setState({ clicked: false }) } render() { return ( <Card border='light' bg='secondary' text='light' className='text-center'> <Card.Header className='h5'>Trip {this.props.by} aggregated by {this.props.agg} <Button variant='primary' size='sm' onClick={this._reset} className='float-sm-right'> Reset </Button> </Card.Header> <Card.Body> <svg className='legend float-left' id={this.props.by + 'legend'} height='110' width='200' style={{ 'zIndex': 1, 'position': 'relative' }}></svg> <DeckGL layers={this._renderLayers()} initialViewState={this.props.initialviewstate} controller={true} style={{ "zIndex": 0 }} > <Map mapStyle={BASEMAP.DARK_MATTER} /> {this._renderTooltip} </DeckGL> </Card.Body> </Card > ) } }
0
rapidsai_public_repos/node/modules/demo/client-server/components
rapidsai_public_repos/node/modules/demo/client-server/components/charts/indicator.jsx
// 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 * as d3 from 'd3'; import * as React from 'react'; import { Card } from 'react-bootstrap'; export default class Indicator extends React.Component { constructor(props) { super(props); this.state = { current_query: this.props.getquery(), size: 0 } } componentDidMount() { this._updateSize() .then((data) => this.setState({ size: d3.format(',')(data) })) .catch((e) => console.log(e)); } componentDidUpdate() { // if parent componet `getquery()` is updated, and is not the same as state.current_query, // refetch the data with current query if (this.props.getquery() !== this.state.current_query) { // update state this.setState({ current_query: this.props.getquery() }); // update data this._updateSize() .then((data) => this.setState({ size: d3.format(',')(data) })) .catch((e) => console.log(e)); } } _generateApiUrl() { const { dataset = undefined, } = this.props; if (!dataset) { return null; } const query = JSON.stringify(this.props.getquery()); return `http://localhost:3000/api/${dataset}/numRows?query_dict=${query}`; } async _updateSize() { const url = this._generateApiUrl(); // `/uber/tracts/groupby/sourceid/mean?columns=travel_time`; if (!url) { return null; } const size = await fetch(url, { method: 'GET' }).then((res) => res.json()).then(data => { return data }); return size; } render() { return ( <Card border='light' bg='secondary' text='light' className='text-center mb-3'> <Card.Header className='h5'>Data Points Selected</Card.Header> <Card.Body> <span className="h4 text-center">{this.state.size}</span> </Card.Body> </Card>) } }
0
rapidsai_public_repos/node/modules/demo/client-server/components
rapidsai_public_repos/node/modules/demo/client-server/components/charts/echarts.bar.jsx
// 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. import { tableFromIPC } from 'apache-arrow'; import * as d3 from 'd3'; import ReactECharts from 'echarts-for-react'; import * as React from 'react'; import { Card } from 'react-bootstrap'; export default class CustomBar extends React.Component { constructor(props) { super(props); this.state = { options: {}, current_query: this.props.getquery(), selected_range: false }; this.echartRef = undefined; this._getOptions = this._getOptions.bind(this); this._onBrushSelected = this._onBrushSelected.bind(this); this._onBrushReset = this._onBrushReset.bind(this); } componentDidMount() { this._updateData() .then((data) => this.setState({ options: this._getOptions(data) })) .catch((e) => console.log(e)); } componentDidUpdate() { // if parent componet `getquery()` is updated, and is not the same as state.current_query, // refetch the data with current query if (this.props.getquery() !== this.state.current_query) { let updateState = { current_query: this.props.getquery() } if (!this.props.getquery().hasOwnProperty(this.props.x)) { // if current chart selections have also been reset updateState['selected_range'] = false; // clear brush if (this.echartRef) { this.echartRef.getEchartsInstance().dispatchAction({ type: 'brush', areas: [] }); } } // update state this.setState(updateState); // update data this._updateData() .then((data) => this.setState({ options: this._getOptions(data) })) .catch((e) => console.log(e)); } } _generateApiUrl() { const { dataset = undefined, x = undefined, agg = undefined, y = undefined // return all columns } = this.props; if (!dataset || !x || !agg) { return null; } const query = JSON.stringify(this.props.getquery()); return `http://localhost:3000/api/${dataset}/groupby/${x}/${agg}?columns=${y}&query_dict=${query}`; } async _updateData() { const url = this._generateApiUrl(); // `/uber/tracts/groupby/sourceid/mean?columns=travel_time`; if (!url) { return null; } const table = await tableFromIPC(fetch(url, { method: 'GET' })); return table.toArray(); } _getOptions(data) { console.log(data); this.setState({ 'x_axis_indices': data.reduce((a, c) => { return [...a, c[this.props.x]] }, []) }) console.log(this.state.x_axis_indices); return { xAxis: { type: 'category', data: this.props.xaxisdata ? this.props.xaxisdata : this.state.x_axis_indices, axisLabel: { color: 'white' }, splitLine: { show: false }, name: 'Trips per ' + this.props.x, nameLocation: 'middle', nameGap: 50, datasetIndex: 0 }, brush: { id: this.props.x, toolbox: ['lineX', 'clear'], throttleType: 'debounce', throttleDelay: 300, xAxisIndex: Object.keys(data) }, yAxis: { type: 'value', axisLabel: { formatter: d3.format('.2s'), color: 'white' }, splitLine: { show: false }, }, series: [{ type: 'bar', id: this.props.x, data: data.reduce((a, c) => { return [...a, c[this.props.y]] }, []) }], tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } }, }; } _onBrushSelected(params) { if (params.batch.length > 0 && params.batch[0].areas.length > 0) { let selected_range = params.batch[0].areas[0].coordRange.map(r => { let idx = (parseInt(r) >= 0) ? parseInt(r) : 0; idx = (idx < this.state.x_axis_indices.length) ? idx : this.state.x_axis_indices.length - 1; return this.state.x_axis_indices[idx]; }); this.props.updatequery({ [this.props.x]: selected_range }); this.setState({ selected_range: selected_range }); } } _onBrushReset(params) { if (!params || params.command == 'clear') { this.props.updatequery({ [this.props.x]: undefined }); this.setState({ selected_range: false }); } } render() { return ( <Card border='light' bg='secondary' text= 'light' className={this.props.className + ' text-center'}> <Card.Header className='h5'>Trips per{this.props.x}</Card.Header> <Card.Body> <ReactECharts option={this.state.options} lazyUpdate={true} onEvents={{ 'brush': this._onBrushReset, 'brushSelected': this._onBrushSelected }} ref={(e) => { this.echartRef = e; }} /> </Card.Body> </Card>) } }
0
rapidsai_public_repos/node/modules/demo/client-server/components
rapidsai_public_repos/node/modules/demo/client-server/components/server/run-middleware.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. export default function runMiddleware(datasetName, req, res, fn) { // Helper method to wait for a middleware to execute before continuing // And to throw an error when an error happens in a middleware return new Promise((resolve, reject) => { fn(datasetName, req, res, (result) => { if (result instanceof Error) { return reject(result) } return resolve(result) }) }) }
0
rapidsai_public_repos/node/modules/demo/client-server/components
rapidsai_public_repos/node/modules/demo/client-server/components/server/cache.js
// 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. const fs = require('fs/promises'); const {DataFrame, Series, Uint32, Int16, Int8, Float32} = require('@rapidsai/cudf'); const {Field, List, vectorFromArray} = require('apache-arrow'); const path = require('path'); module.exports = () => { let timeout = null; let datasets = {uber: null, mortgage: null} // let uberTracts = null; function clearCachedGPUData() { datasets.uber = null; datasets.mortgage = null; } return async function loadDataMiddleware(datasetName, req, res, next) { if (timeout) { clearTimeout(timeout); } // Set a 10-minute debounce to release server GPU memory timeout = setTimeout(clearCachedGPUData, 10 * 60 * 1000); req[datasetName] = datasets[datasetName] || (datasets[datasetName] = await readDataset(datasets, datasetName)); next(); } } async function readDataset(datasets, datasetName) { if (datasetName == 'uber') { // clear mortgage dataset from mem datasets.mortgage = null; return readUberTrips(); } if (datasetName == 'mortgage') { // clear uber dataset from mem datasets.uber = null; return readMortgageData(); } } async function readUberTrips() { const trips = DataFrame.readCSV({ header: 0, sourceType: 'files', sources: [path.resolve('./public', 'data/san_fran_uber.csv')], dataTypes: { sourceid: new Int16, dstid: new Int16, month: new Int8, day: new Int8, start_hour: new Int8, end_hour: new Int8, travel_time: new Float32 } }); return new DataFrame({ // TODO: do we want to add our own indices? // id: Series.sequence({ type: new Uint32, init: 0, size: trips.numRows }), sourceid: trips.get('sourceid'), dstid: trips.get('dstid'), month: trips.get('month'), day: trips.get('day'), start_hour: trips.get('start_hour'), end_hour: trips.get('end_hour'), travel_time: trips.get('travel_time'), }); } async function readMortgageData() { const mortgage = DataFrame.readCSV({ header: 0, sourceType: 'files', sources: [path.resolve('./public', 'data/mortgage.csv')], dataTypes: { index: new Int16, zip: new Uint32, dti: new Float32, current_actual_upb: new Float32, borrower_credit_score: new Int16, load_id: new Uint32, delinquency_12_prediction: new Float32, seller_name: new Int16 } }); return new DataFrame({ // TODO: do we want to add our own indices? // id: Series.sequence({ type: new Uint32, init: 0, size: trips.numRows }), zip: mortgage.get('zip'), dti: mortgage.get('dti'), current_actual_upb: mortgage.get('current_actual_upb'), borrower_credit_score: mortgage.get('borrower_credit_score'), load_id: mortgage.get('load_id'), delinquency_12_prediction: mortgage.get('delinquency_12_prediction'), seller_name: mortgage.get('seller_name'), }); } async function readUberTracts() { const {features} = JSON.parse( await fs.readFile('public/data/san_francisco_censustracts.geojson', {encoding: 'utf8'})); const polygons = features.filter((f) => f.geometry.type === 'MultiPolygon') .reduce((x, {geometry}) => x.concat(geometry.coordinates), []); return new DataFrame({ id: Series.sequence({type: new Uint32, init: 0, size: polygons.length}), polygons: Series.new(featureToVector(polygons)) }); function featureToVector(coordinates) { return vectorFromArray( coordinates, new List(Field.new({ name: 'rings', type: new List(Field.new( {name: 'coords', type: new List(Field.new({name: 'points', type: new Float32()}))})) })), ); } }
0
rapidsai_public_repos/node/modules/demo/client-server/components
rapidsai_public_repos/node/modules/demo/client-server/components/server/cudf-utils.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. const { performance } = require('perf_hooks'); const { RecordBatchStreamWriter } = require('apache-arrow'); //A module method to pipe between streams and generators forwarding errors and properly cleaning up and provide a callback when the pipeline is complete. const pipeline = require('util').promisify(require('stream').pipeline); /** * Computes cuDF.Column eq operation on given column and value. * * @param df cuDF.DataFrame * @param column str, column name * @param value number * @returns Boolean mask result of column == value */ function filterByValue(df, column, value) { return df.get(column).eq(value); } /** * Computes cuDF.Column gt, lt and eq operations on given column and min, max values. * * @param df cuDF.DataFrame * @param column str, column name * @param minMaxArray Array * @returns Boolean mask result of min <= column <= max */ function filterByRange(df, column, minMaxArray) { const [min, max] = minMaxArray; const boolmask_gt_eq = (df.get(column).gt(min)).logicalOr(df.get(column).eq(min)) const boolmask_lt_eq = (df.get(column).lt(max)).logicalOr(df.get(column).eq(max)) return boolmask_gt_eq.logicalAnd(boolmask_lt_eq) } /** * Computes cuDF.DataFrame.filter by parsing input query_dictionary, and performing filterByValue or * filterByRange as needed. * * @param query_dict {}, where key is column name, and value is either scalar value, or a range of * scalar values * @param ignore str, column name which is to be ignored (if any) from query compute * @returns resulting cuDF.DataFrame */ function parseQuery(df, query_dict, ignore = null) { let t0 = performance.now(); if (ignore && ignore in query_dict) { delete query_dict[ignore]; } let boolmask = undefined; Object.keys(query_dict) .filter(key => df._accessor.names.includes(key)) .forEach(key => { //check if query is range of values if (Array.isArray(query_dict[key]) && query_dict[key].length == 2) { boolmask = boolmask ? boolmask.logicalAnd(filterByRange(df, key, query_dict[key])) : filterByRange(df, key, query_dict[key]); } //check if query is a number else if (typeof (query_dict[key]) == "number") { boolmask = boolmask ? boolmask.logicalAnd(filterByValue(df, key, query_dict[key])) : filterByValue(df, key, query_dict[key]); } }) if (boolmask) { df = df.filter(boolmask); } console.log(`Query ${JSON.stringify(query_dict)} Time Taken: ${(performance.now() - t0).toFixed(2)}ms`); return df; } async function groupBy(df, by, aggregation, columns, query_dict, res) { console.log('\n\n'); // filter the dataframe as the query_dict & ignore the by column (to make sure chart selection doesn't filter self) if (query_dict && Object.keys(query_dict).length > 0) { df = parseQuery(df, query_dict, by); } // Perf: only include the subset of columns we want to return in `df.groupBy()[agg]()` const colsToUse = columns || df.names.filter((n) => n !== by); let t0; try { t0 = performance.now(); let trips = df.select([by, ...colsToUse]).groupBy({ by })[aggregation](); console.log(`trips.groupBy({by:${by}}).${aggregation}() Time Taken: ${(performance.now() - t0).toFixed(2)}ms`); t0 = performance.now(); trips = trips.sortValues({ [by]: { ascending: true, null_order: 'after' } }); console.log(`trips.sortValues({${by}}) Time Taken: ${(performance.now() - t0).toFixed(2)}ms`); //stream data to client, where `arrow.Table(fetch(url, {method:'GET'}))` consumes it await pipeline( RecordBatchStreamWriter.writeAll(trips.toArrow()).toNodeStream(), res.writeHead(200, 'Ok', { 'Content-Type': 'application/octet-stream' }) ); trips = null; } catch (e) { res.status(500).send(e ? `${(e.stack || e.message)}` : 'Unknown error'); } // TODO in future, when binary data input to geoJSONLayer in deck.gl is implemented, // offload the geojson geometry gather calculations to the server-side // t0 = performance.now(); // const tracts = req.uberTracts.gather(trips.get(by)) // .assign((columns || []).reduce((cols, col) => ({ // ...cols, [col]: trips.get(col) // }), {})); // console.log(`tracts.gather(trips.get(${by})) Time Taken: ${(performance.now() - t0).toFixed(2)}ms`); } async function numRows(df, query_dict, res) { let t0 = performance.now(); console.log('\n\n'); // filter the dataframe as the query_dict & ignore the by column (to make sure chart selection doesn't filter self) if (query_dict && Object.keys(query_dict).length > 0) { df = parseQuery(df, query_dict); } console.log(`trips.query(${JSON.stringify(query_dict)}).numRows Time Taken: ${(performance.now() - t0).toFixed(2)}ms`); res.send(df.numRows); } export { groupBy, numRows }
0
rapidsai_public_repos/node/modules/demo/client-server/public
rapidsai_public_repos/node/modules/demo/client-server/public/data/SOURCES.md
# Notebook demo data sources * [US_Accidents_Dec20.csv](https://www.kaggle.com/sobhanmoosavi/us-accidents?select=US_Accidents_Dec20.csv) * [san_francisco_censustracts.geojson](https://movement.uber.com/explore/san_francisco/travel-times/query?lang=en-US&si=1277&ti=&ag=censustracts&dt[tpb]=ALL_DAY&dt[wd;]=1,2,3,4,5,6,7&dt[dr][sd]=2020-03-01&dt[dr][ed]=2020-03-31&cd=&sa;=&sdn=&lat.=37.7749295&lng.=-122.4547777&z.=12) `Download data > Geo Boundaries > SAN_FRANCISCO_CENSUSTRACTS.JSON` * [san_fran_uber.csv](https://movement.uber.com/explore/san_francisco/travel-times/query?lang=en-US&si=1277&ti=&ag=censustracts&dt[tpb]=ALL_DAY&dt[wd;]=1,2,3,4,5,6,7&dt[dr][sd]=2020-03-01&dt[dr][ed]=2020-03-31&cd=&sa;=&sdn=&lat.=37.7749295&lng.=-122.4547777&z.=12) `Download data > All data > 2020 Quarter > Travel Times By Date By Hour Buckets (All Days) (1.7gb)`
0
rapidsai_public_repos/node/modules/demo/client-server/public
rapidsai_public_repos/node/modules/demo/client-server/public/data/san_francisco_censustracts.geojson
version https://git-lfs.github.com/spec/v1 oid sha256:05a9ea1a1d11be4804db6e21d6f2ef266aee440b7e43ad2d9de0971585a49ba2 size 3786304
0
rapidsai_public_repos/node/modules/demo/client-server
rapidsai_public_repos/node/modules/demo/client-server/pages/index.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 Head from 'next/head' import Layout from '../components/layout' import { Row, Col, Card, CardGroup, Button } from 'react-bootstrap'; import Link from 'next/link' export default function Home() { return ( <Layout title="Node-rapids Demos" displayReset="false"> <Head> <title></title> </Head> <section > <p className="h4 text-white text-center">A collection of client server demos powered by node-rapids for compute and streaming from the server, to a react client. </p> <CardGroup> <Card variant="secondary" text="light"> <Card.Img variant="top" src="/images/uber.png" style={{ "height": "350px" }} /> <Card.Body className="text-center"> <Card.Title>Uber Movement Dashboard</Card.Title> <Card.Text> <Link href="/dashboard/uber"> <Button variant="primary">Start Dashboard </Button> </Link> </Card.Text> </Card.Body> </Card> <Card variant="secondary" text="light"> <Card.Img variant="top" src="/images/mortgage.png" style={{ "height": "350px" }} /> <Card.Body className="text-center"> <Card.Title>Fannie Mae Mortgage Dashboard</Card.Title> <Card.Text> <Link href="/dashboard/mortgage"> <Button variant="primary">Start Dashboard </Button> </Link> </Card.Text> </Card.Body> </Card> </CardGroup> </section > <footer className="text-center" style={{ "position": "fixed", "bottom": 50, "width": "100%", "textAlign": "center" }}> <Row> <Col><a href="https://github.com/rapidsai/node-rapids/" target="_blank"> node-rapids github </a>{' '}</Col> <Col><a href="https://github.com/rapidsai/" target="_blank"> Explore other RAPIDS projects </a> </Col> <Col><a href="https://nextjs.org/learn" target="_blank">Next.js</a></Col> </Row> </footer> </Layout > ) }
0
rapidsai_public_repos/node/modules/demo/client-server
rapidsai_public_repos/node/modules/demo/client-server/pages/_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 '../styles/global.css' export default function App({ Component, pageProps }) { return <Component {...pageProps} /> }
0
rapidsai_public_repos/node/modules/demo/client-server/pages
rapidsai_public_repos/node/modules/demo/client-server/pages/api/[...param].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 runMiddleware from '../../components/server/run-middleware'; import { groupBy, numRows } from '../../components/server/cudf-utils'; const cache = require('../../components/server/cache')(); export default async function handler(req, res) { const [dataset, fn, by, aggregation] = req.query.param; await runMiddleware(dataset, req, res, cache); const query_dict = req.query.query_dict ? JSON.parse(req.query.query_dict) : undefined; // `query.columns` could be a string, or an Array of strings. // This flattens either case into a single Array, or defaults to null. const columns = req.query.columns ? [].concat(req.query.columns.split(',')) : null; // const columns = req.query.columns ? JSON.parse(req.query.columns) : undefined; console.log(columns); if (fn == "groupby") { groupBy(req[dataset], by, aggregation, columns, query_dict, res); } else if (fn == "numRows") { numRows(req[dataset], query_dict, res); } } export const config = { api: { externalResolver: true, bodyParse: false, }, }
0
rapidsai_public_repos/node/modules/demo/client-server/pages
rapidsai_public_repos/node/modules/demo/client-server/pages/dashboard/uber.jsx
// 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 * as d3 from 'd3'; import Head from 'next/head'; import * as React from 'react'; import { Col, Container, Row } from 'react-bootstrap'; import CustomChoropleth from '../../components/charts/deck.geo.jsx'; import CustomBar from '../../components/charts/echarts.bar.jsx'; import Indicator from '../../components/charts/indicator.jsx'; import Layout from '../../components/layout'; // color scale for choropleth charts const COLOR_SCALE = [ [49, 130, 189, 100], [107, 174, 214, 100], [123, 142, 216, 100], [226, 103, 152, 100], [255, 0, 104, 100], ]; const thresholdScale = d3.scaleThreshold().domain([0, 400, 800, 1000, 2000, 4000]).range(COLOR_SCALE); export default class UberDashboard extends React.Component { constructor(props) { super(props); this.state = { query_dict: {} }; this._getQuery = this._getQuery.bind(this); this._resetQuery = this._resetQuery.bind(this); this._updateQuery = this._updateQuery.bind(this); } _getQuery() { return this.state.query_dict; } _resetQuery() { this.setState({ query_dict: {} }); } _updateQuery(query_dict) { query_dict = { ...this.state.query_dict, ...query_dict }; this.setState({ query_dict: query_dict }) } render() { return ( <Layout title='Uber Dashboard' resetall={this._resetQuery}> <Head> <title>Uber Dashboard</title> </Head> <Container fluid> <Row> <Col md={3}> <Col> <Indicator dataset='uber' getquery={this._getQuery} updatequery={this._updateQuery} /> </Col> <Col> <CustomBar dataset='uber' x='day' y='sourceid' agg='count' getquery={this._getQuery} updatequery={this._updateQuery} xaxisdata={Array.from({ length: 31 }, (v, k) => k + 1)} className='mb-3' /> </Col> <Col> <CustomBar dataset='uber' x='start_hour' y='sourceid' agg='count' getquery={this._getQuery} updatequery={this._updateQuery} xaxisdata={['AM Peak', 'Midday', 'PM Peak', 'Evening', 'Early Morning']} /> </Col> </Col> <Col md={9}> <Row> <Col md={6}> <CustomChoropleth dataset="uber" by="sourceid" agg="mean" columns={["travel_time"]} geojsonurl="http://localhost:3000/data/san_francisco_censustracts.geojson" geojsonprop="MOVEMENT_ID" initialviewstate={{ longitude: -122, latitude: 37, zoom: 6, maxZoom: 16, pitch: 0, bearing: 0 }} getquery={this._getQuery} updatequery={this._updateQuery} thresholdScale={thresholdScale} legend_props={{ 0: '0s to 400s', 500: '400s to 800s', 900: '800s to 1000s', 1100: '1000s or higher', }} /> </Col> <Col md={6}> <CustomChoropleth dataset='uber' by='dstid' agg='mean' columns={['travel_time', 'DISPLAY_NAME']} geojsonurl= 'http://localhost:3000/data/san_francisco_censustracts.geojson' geojsonprop='MOVEMENT_ID' initialviewstate={{ longitude: -122, latitude: 37, zoom: 6, maxZoom: 16, pitch: 0, bearing: 0 }} getquery={this._getQuery} updatequery={this._updateQuery} thresholdScale={thresholdScale} legend_props={{ 0: '0s to 400s', 500: '400s to 800s', 900: '800s to 1000s', 1100: '1000s or higher' }} /> </Col> </Row> </Col> </Row> </Container> </Layout> ); } }
0
rapidsai_public_repos/node/modules/demo/client-server/pages
rapidsai_public_repos/node/modules/demo/client-server/pages/dashboard/mortgage.jsx
// 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 * as d3 from 'd3'; import Head from 'next/head'; import * as React from 'react'; import { Col, Container, Row } from 'react-bootstrap'; import CustomChoropleth from '../../components/charts/deck.geo.jsx'; import CustomBar from '../../components/charts/echarts.bar.jsx'; import Indicator from '../../components/charts/indicator.jsx'; import Layout from '../../components/layout'; // color scale for choropleth charts const COLOR_SCALE = [ [49, 130, 189, 100], [107, 174, 214, 100], [123, 142, 216, 100], [226, 103, 152, 100], [255, 0, 104, 100], ]; const thresholdScale = d3.scaleThreshold().domain([0, 0.196, 0.198, 0.200, 0.202]).range(COLOR_SCALE); export default class MortgageDashboard extends React.Component { constructor(props) { super(props); this.state = { query_dict: {} }; this._getQuery = this._getQuery.bind(this); this._resetQuery = this._resetQuery.bind(this); this._updateQuery = this._updateQuery.bind(this); } _getQuery() { return this.state.query_dict; } _resetQuery() { this.setState({ query_dict: {} }); } _updateQuery(query_dict) { query_dict = { ...this.state.query_dict, ...query_dict }; this.setState({ query_dict: query_dict }) } render() { return ( <Layout title='Fannie Mae Mortgage Dashboard' resetall={this._resetQuery}> <Head> <title>Fannie Mae Mortgage Dashboard</title> </Head> <Container fluid> <Row> <Col md={3}> <Col> <Indicator dataset='mortgage' getquery={this._getQuery} updatequery={this._updateQuery} /> </Col> <Col> <CustomBar dataset='mortgage' x='dti' y='zip' agg='count' getquery={this._getQuery} updatequery={this._updateQuery} className='mb-3' /> </Col> <Col> <CustomBar dataset='mortgage' x='borrower_credit_score' y='zip' agg='count' getquery={this._getQuery} updatequery={this._updateQuery} /> </Col> </Col> <Col md={9}> <CustomChoropleth dataset="mortgage" by="zip" agg="mean" columns={['delinquency_12_prediction', 'current_actual_upb', 'dti', 'borrower_credit_score']} fillcolor="delinquency_12_prediction" elevation="current_actual_upb" geojsonurl="https://raw.githubusercontent.com/rapidsai/cuxfilter/GTC-2018-mortgage-visualization/javascript/demos/GTC%20demo/src/data/zip3-ms-rhs-lessprops.json" geojsonprop='ZIP3' initialviewstate={{ longitude: -101, latitude: 37, zoom: 3, maxZoom: 16, pitch: 0, bearing: 0 }} getquery={this._getQuery} updatequery={this._updateQuery} thresholdScale={thresholdScale} legend_props={{ '0.100': '0 to 0.196', '0.197': '0.196 to 0.198', '0.199': '0.198 to 0.200', '0.201': '0.200 to 0.202', '0.203': '0.202 to 0.2+' }} /> </Col> </Row> </Container> </Layout> ) } }
0
rapidsai_public_repos/node/modules/demo/ssr
rapidsai_public_repos/node/modules/demo/ssr/graph/package.json
{ "private": true, "name": "@rapidsai/demo-graph-ssr", "main": "index.js", "version": "22.12.2", "license": "Apache-2.0", "author": "NVIDIA, Inc. (https://nvidia.com/)", "maintainers": [ "Paul Taylor <[email protected]>" ], "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/cuda": "~22.12.2", "@rapidsai/deck.gl": "~22.12.2", "@rapidsai/jsdom": "~22.12.2", "fastify": "3.20.2", "fastify-plugin": "3.0.0", "fastify-socket.io": "2.0.0", "fastify-static": "4.4.1", "nanoid": "3.1.31", "rxjs": "6.6.7", "shm-typed-array": "0.0.16", "simple-peer": "9.11.0", "socket.io": "4.1.3" }, "files": [ "render", "public", "plugins", "index.js", "package.json" ] }
0
rapidsai_public_repos/node/modules/demo/ssr
rapidsai_public_repos/node/modules/demo/ssr/graph/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. const fastify = require('fastify')(); fastify // .register(require('./plugins/webrtc'), require('./plugins/graph')(fastify)) .register(require('fastify-static'), {root: require('path').join(__dirname, 'public')}) .get('/', (req, reply) => reply.sendFile('video.html')); fastify.listen(8080).then(() => console.log('server ready'));
0
rapidsai_public_repos/node/modules/demo/ssr
rapidsai_public_repos/node/modules/demo/ssr/graph/README.md
# Graph Server Side Rendering (SSR) and Streaming Server The back end to the [Viz-App](https://github.com/rapidsai/node/tree/main/modules/demo/viz-app) demo, using cuGraph FA2, luma.gl for visualization, and default graph data. Streamed using webRTC utilizing [nvENC](https://docs.nvidia.com/video-technologies/video-codec-sdk/nvenc-video-encoder-api-prog-guide/). ## Featured Dependencies - @rapidsai/cudf - @rapidsai/cugraph - @rapidsai/jsdom - @rapidsai/deckgl ## Data Requirements The graph demo will default to internal data. ## Start To start the server: ```bash yarn start #NOTE: For the demo to work, run this in one terminal instance AND run the Viz-App in another terminal (use graph option) ```
0
rapidsai_public_repos/node/modules/demo/ssr/graph
rapidsai_public_repos/node/modules/demo/ssr/graph/render/worker.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. const {fromEvent, EMPTY} = require('rxjs'); const {tap, groupBy, mergeMap, concatMap} = require('rxjs/operators'); const {Renderer} = require('./render'); const renderer = new Renderer(); function render({props = {}, graph = {}, state = {}, event = [], frame = 0}) { return renderer.render(props, graph, state, event, frame); } fromEvent(process, 'message', (x) => x) .pipe(groupBy(({type}) => type)) .pipe(mergeMap((group) => { switch (group.key) { case 'exit': return group.pipe(tap(({code}) => process.exit(code))); case 'render.request': return group // .pipe(concatMap(({data}) => render(data), ({id}, data) => ({id, data}))) // .pipe(tap((result) => send({...result, type: 'render.result'}))); } return EMPTY; })) .subscribe(); function send(x) { try { JSON.stringify(x); process.send(x); } catch (e) { debugger; } }
0
rapidsai_public_repos/node/modules/demo/ssr/graph
rapidsai_public_repos/node/modules/demo/ssr/graph/render/render.js
// Copyright (c) 2021-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. const {IpcMemory, Uint8Buffer} = require('@rapidsai/cuda'); const {RapidsJSDOM} = require('@rapidsai/jsdom'); const copyFramebuffer = require('./copy')(); class Renderer { constructor() { const onAnimationFrameRequested = immediateAnimationFrame(this); const jsdom = new RapidsJSDOM({ module, onAnimationFrameRequested, babel: { presets: [ // transpile all ESM to CJS ['@babel/preset-env', {targets: {node: 'current'}}], ...RapidsJSDOM.defaultOptions.babel.presets, ] }, }); const {deck, render} = jsdom.window.evalFn(makeDeck); this.deck = deck; this.jsdom = jsdom; this._render = render; } async render(props = {}, graph = {}, state = {}, events = [], frame = 0) { const window = this.jsdom.window; graph = openGraphIpcHandles(graph); props && this.deck.setProps(props); state?.deck && this.deck.restore(state.deck); state?.graph && Object.assign(graph, state.graph); state?.window && Object.assign(window, state.window); (events || []).forEach((event) => window.dispatchEvent(event)); await this._render(graph); closeIpcHandles(graph.data.nodes); closeIpcHandles(graph.data.edges); const deck = this.deck.serialize(); return { frame: copyFramebuffer(this.deck.animationLoop, frame), state: { ...state, deck: { ...deck, props: { ...deck.props, boxSelection: this.deck?.props?.boxSelection, selectedNodes: this.deck?.props?.selectedNodes, selectedEdges: this.deck?.props?.selectedEdges, } }, graph: this.deck.layerManager.getLayers() ?.find((layer) => layer.id === 'GraphLayer') .serialize(), window: { x: window.x, y: window.y, title: window.title, width: window.width, height: window.height, cursor: window.cursor, mouseX: window.mouseX, mouseY: window.mouseY, buttons: window.buttons, scrollX: window.scrollX, scrollY: window.scrollY, modifiers: window.modifiers, mouseInWindow: window.mouseInWindow, } } }; } } module.exports.Renderer = Renderer; function immediateAnimationFrame(renderer) { let request = null; let flushing = false; const flush = () => { flushing = true; while (request && request.active) { const f = request.flush; request = null; f(); } flushing = false; }; return (r) => { if (flushing) { return request = r; } if (renderer?.deck?.animationLoop?._initialized) { // return flush(request = r); } if (!request && (request = r)) { setImmediate(flush); } }; } function makeDeck() { const {log: deckLog} = require('@deck.gl/core'); deckLog.level = 0; deckLog.enable(false); const {OrthographicView} = require('@deck.gl/core'); const {TextLayer, PolygonLayer} = require('@deck.gl/layers'); const {DeckSSR, GraphLayer} = require('@rapidsai/deck.gl'); const makeLayers = (deck, graph = {}) => { const boxSelection = deck?.props?.boxSelection; const [viewport] = (deck?.viewManager?.getViewports() || []); const [minX = Number.NEGATIVE_INFINITY, minY = Number.NEGATIVE_INFINITY, ] = viewport?.getBounds() || []; return [ new TextLayer({ sizeScale: 1, opacity: 0.9, maxWidth: 2000, pickable: false, getTextAnchor: 'start', getAlignmentBaseline: 'top', getSize: ({size}) => size, getColor: ({color}) => color, getPixelOffset: ({offset}) => offset, data: Array.from({length: +process.env.NUM_WORKERS}, (_, i) => // ({ size: 15, offset: [0, i * 15], text: `Worker ${i}`, position: [minX, minY], color: +process.env.WORKER_ID === i // ? [245, 171, 53, 255] : [255, 255, 255, 255], })) }), new GraphLayer({pickable: true, ...graph}), new PolygonLayer({ filled: true, stroked: true, getPolygon: d => d.polygon, lineWidthUnits: 'pixels', getLineWidth: 2, getLineColor: [80, 80, 80], getLineColor: [0, 0, 0, 150], getFillColor: [255, 255, 255, 65], data: boxSelection ? [boxSelection] : [] }) ]; }; function onDragStart(info, event) { if (event?.srcEvent?.shiftKey) { event.preventDefault(); const {x, y} = info; const [px, py] = info.viewport.unproject([x, y]); deck.setProps({ boxSelection: { origin: [x, y], polygon: [[px, py], [px, py], [px, py], [px, py]], } }); return true; } } function onDrag(info, event) { if (deck.props.boxSelection) { event.preventDefault(); const {x, y} = info; const [px, py] = info.viewport.unproject([x, y]); const [[sx, sy]] = deck.props.boxSelection.polygon; deck.setProps({ boxSelection: { ...deck.props.boxSelection, polygon: [[sx, sy], [sx, py], [px, py], [px, sy]], } }); return true; } }; function onDragEnd(info, event) { if (deck.props.boxSelection) { event.preventDefault(); const {x, y} = info; const [sx, sy] = deck.props.boxSelection.origin; const selections = deck.pickObjects({ x: Math.min(sx, x), y: Math.min(sy, y), width: Math.abs(x - sx), height: Math.abs(y - sy), layerIds: ['GraphLayer'] }); deck.setProps({ boxSelection: null, selectedNodes: selections.filter(x => x.hasOwnProperty('nodeId')).map(n => n.nodeId), selectedEdges: selections.filter(x => x.hasOwnProperty('edgeId')).map(n => n.edgeId), }); if (deck.props.selectedNodes.length > 0) { console.log({'selected nodes': deck.props.selectedNodes}); } if (deck.props.selectedEdges.length > 0) { console.log({'selected edges': deck.props.selectedEdges}); } return true; } } function onClick(info, event) { const selections = deck.pickObjects({ x: info.x, y: info.y, radius: 1, }); deck.setProps({ boxSelection: null, selectedNodes: selections.filter(x => x.hasOwnProperty('nodeId')).map(n => n.nodeId), selectedEdges: selections.filter(x => x.hasOwnProperty('edgeId')).map(n => n.edgeId), }); if (deck.props.selectedNodes.length > 0) { console.log({'selected nodes': deck.props.selectedNodes}); } if (deck.props.selectedEdges.length > 0) { console.log({'selected edges': deck.props.selectedEdges}); } } const deck = new DeckSSR({ _sync: true, createFramebuffer: true, initialViewState: { zoom: 1, target: [0, 0, 0], minZoom: Number.NEGATIVE_INFINITY, maxZoom: Number.POSITIVE_INFINITY, }, layers: [makeLayers(null, {})], views: [ new OrthographicView({ clear: { color: [...[46, 46, 46].map((x) => x / 255), 1], }, controller: { keyboard: false, doubleClickZoom: false, scrollZoom: {speed: 0.01, smooth: false}, } }), ], onAfterAnimationFrameRender({_loop}) { _loop.pause(); }, onClick, onDrag, onDragStart, onDragEnd, selectedNodes: [], selectedEdges: [], }); return { deck, render(graph) { const done = deck.animationLoop.waitForRender(); deck.setProps({layers: makeLayers(deck, graph)}); deck.animationLoop.start(); return done; }, }; } function openGraphIpcHandles({nodes, edges, ...graphLayerProps} = {}) { const data = { nodes: openNodeIpcHandles(nodes), edges: openEdgeIpcHandles(edges), }; return { pickable: true, edgeOpacity: .5, edgeStrokeWidth: 2, nodesStroked: true, nodeFillOpacity: .5, nodeStrokeOpacity: .9, nodeRadiusScale: 1 / 75, nodeRadiusMinPixels: 5, nodeRadiusMaxPixels: 150, ...graphLayerProps, data, numNodes: data.nodes.length, numEdges: data.edges.length, }; } function openNodeIpcHandles(attrs = {}) { const positions = openIpcHandle(attrs.positions); const attributes = { nodeRadius: openIpcHandle(attrs.nodeRadius), nodeXPositions: positions.subarray(0, positions.length / 2), nodeYPositions: positions.subarray(positions.length / 2), nodeFillColors: openIpcHandle(attrs.nodeFillColors), nodeElementIndices: openIpcHandle(attrs.nodeElementIndices), }; return {offset: 0, length: attrs.length ?? (attributes.nodeRadius?.byteLength || 0), attributes}; } function openEdgeIpcHandles(attrs = {}) { const attributes = { edgeList: openIpcHandle(attrs.edgeList), edgeColors: openIpcHandle(attrs.edgeColors), edgeBundles: openIpcHandle(attrs.edgeBundles), }; return { offset: 0, length: attrs.length ?? (attributes.edgeList?.byteLength || 0) / 8, attributes }; } function openIpcHandle(obj) { if (typeof obj === 'string') { obj = JSON.parse(obj); } if (obj) { const {byteOffset = 0} = obj; const handle = Uint8Array.from(obj.handle.map(Number)); return new Uint8Buffer(new IpcMemory(handle)).subarray(byteOffset); } return null; } function closeIpcHandles(obj) { for (const key in obj) { const {buffer} = obj[key] || {}; if (buffer && (buffer instanceof IpcMemory)) { // buffer.close(); } } }
0
rapidsai_public_repos/node/modules/demo/ssr/graph
rapidsai_public_repos/node/modules/demo/ssr/graph/render/cluster.js
// Copyright (c) 2021-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. const workerPath = require('path').join(__dirname, 'worker.js'); class RenderCluster { constructor({fps = 60, numWorkers = 4} = {}) { this._fps = fps; this._timerId = null; this._reqs = Object.create(null); this._jobs = Object.create(null); this._workers = this._createWorkers(numWorkers); process.on('exit', killWorkers); process.on('beforeExit', killWorkers); function killWorkers(code = 'SIGKILL') { this._workers.forEach((worker) => { if (!worker.killed) { worker.send({type: 'exit', code}); worker.kill(code); } }); } } pause() { if (this._timerId !== null) { clearInterval(this._timerId); this._timerId = null; } } start() { if (this._timerId === null) { this._timerId = setInterval(() => this.flush(), 1000 / this._fps); } } render(id, data, callback) { const request = this._reqs[id] || (this._reqs[id] = Object.create(null)); (request.callbacks || (request.callbacks = [])).push(callback); request.data || (request.data = Object.create(null)); Object.assign(request.data, data); this.start(); } flush() { const requests = this._reqs; this._reqs = Object.create(null); const workers = this._workers.slice().sort((a, b) => a.jobs - b.jobs); let workerId = 0; for (const id in requests) { if (!(id in this._jobs)) { this._jobs[id] = dispatchJob(id, requests, workers[workerId]); workerId = (workerId + 1) % workers.length; } } } _onWorkerExit(workerId, ...xs) { console.log(`worker ${workerId} exit`, ...xs); } _onWorkerError(workerId, ...xs) { console.log(`worker ${workerId} error`, ...xs); } _onWorkerClose(workerId, ...xs) { console.log(`worker ${workerId} close`, ...xs); } _onWorkerDisconnect(workerId, ...xs) { console.log(`worker ${workerId} disconnect`, ...xs); } _onWorkerMessage(_workerId, {id, type, data}) { switch (type) { case 'render.result': const p = this._jobs[id]; delete this._jobs[id]; return p && p.resolve(data); } } _createWorkers(numWorkers = 4) { return Array.from({length: numWorkers}).map((_, i) => { const worker = require('child_process').fork(workerPath, { cwd: __dirname, // serialization: 'advanced', execArgv: ['--trace-uncaught'], stdio: ['pipe', 'inherit', 'inherit', 'ipc'], env: { ...process.env, DISPLAY: undefined, WORKER_ID: i, NUM_WORKERS: numWorkers, }, }); worker.jobs = 0; return worker.on('exit', this._onWorkerExit.bind(this, i)) .on('error', this._onWorkerError.bind(this, i)) .on('close', this._onWorkerClose.bind(this, i)) .on('message', this._onWorkerMessage.bind(this, i)) .on('disconnect', this._onWorkerDisconnect.bind(this, i)); }); } } function dispatchJob(id, requests, worker) { const {promise, resolve, reject} = promiseSubject(); promise .catch((err) => { if (id in requests) { --worker.jobs; const {callbacks} = requests[id]; delete requests[id]; callbacks.forEach((cb) => cb(err, null)); } }) .then((data) => { if (id in requests) { --worker.jobs; const {callbacks} = requests[id]; delete requests[id]; callbacks.forEach((cb) => cb(null, data)); } }); const data = {...requests[id].data}; ++worker.jobs; worker.send({id, type: 'render.request', data}); return {promise, resolve, reject}; } function promiseSubject() { let resolve, reject; let promise = new Promise((r1, r2) => { resolve = r1; reject = r2; }); return {promise, resolve, reject}; } module.exports.RenderCluster = RenderCluster;
0
rapidsai_public_repos/node/modules/demo/ssr/graph
rapidsai_public_repos/node/modules/demo/ssr/graph/render/copy.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. const {CUDA, Uint8Buffer} = require('@rapidsai/cuda'); const {Buffer: DeckBuffer} = require('@rapidsai/deck.gl'); const {Framebuffer, readPixelsToBuffer} = require('@luma.gl/webgl'); const shm = require('shm-typed-array'); Object.defineProperty(Framebuffer, Symbol.hasInstance, { value: (x) => x?.constructor?.name === 'Framebuffer', }); module.exports = copyAndConvertFramebuffer; function copyAndConvertFramebuffer() { let i420DeviceBuffer = null; let rgbaDeviceBuffer = null; return ({gl, framebuffer}, sharedMemoryKey) => { const {width, height} = framebuffer; const rgbaByteLength = width * height * 4; const i420ByteLength = width * height * 3 / 2; if (rgbaDeviceBuffer?.byteLength !== rgbaByteLength) { rgbaDeviceBuffer?.delete({deleteChildren: true}); rgbaDeviceBuffer = new DeckBuffer(gl, { byteLength: rgbaByteLength, accessor: {type: gl.UNSIGNED_BYTE, size: 4}, }); } if (i420DeviceBuffer?.byteLength !== i420ByteLength) { i420DeviceBuffer = new Uint8Buffer(i420ByteLength); } // DtoD copy from framebuffer into our pixelbuffer readPixelsToBuffer( framebuffer, {sourceType: gl.UNSIGNED_BYTE, sourceFormat: gl.RGBA, target: rgbaDeviceBuffer}); // Map and unmap the GL buffer as a CUDA buffer rgbaDeviceBuffer.asMappedResource((glBuffer) => { const cuBuffer = glBuffer.asCUDABuffer(0, rgbaByteLength); // flip horizontally to account for WebGL's coordinate system (e.g. ffmpeg -vf vflip) CUDA.rgbaMirror(width, height, 0, cuBuffer); // convert colorspace from OpenGL's BGRA to WebRTC's IYUV420 CUDA.bgraToYCrCb420(i420DeviceBuffer, cuBuffer, width, height); }); // DtoH copy for output const out = shm.get(sharedMemoryKey, 'Uint8ClampedArray'); i420DeviceBuffer.copyInto(out); shm.detach(sharedMemoryKey); return {width, height, data: sharedMemoryKey}; }; }
0
rapidsai_public_repos/node/modules/demo/ssr/graph
rapidsai_public_repos/node/modules/demo/ssr/graph/plugins/webrtc.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. const wrtc = require('wrtc'); const Peer = require('simple-peer'); module.exports = require('fastify-plugin')(function(fastify, opts, next) { fastify .register(require('fastify-socket.io')) // .after(() => fastify.io.on('connect', onConnect)); next(); function onConnect(sock) { const peer = new Peer({ wrtc, sdpTransform: (sdp) => { // Remove bandwidth restrictions // https://github.com/webrtc/samples/blob/89f17a83ed299ef28d45b933419d809b93d41759/src/content/peerconnection/bandwidth/js/main.js#L240 sdp = sdp.replace(/b=AS:.*\r\n/, '').replace(/b=TIAS:.*\r\n/, ''); return sdp; } }); peer.on('close', onClose); peer.on('error', onError); peer.on('connect', onConnect); sock.on('disconnect', () => peer.destroy()); // Handle signaling sock.on('signal', (data) => { peer.signal(data); }); peer.on('signal', (data) => { sock.emit('signal', data); }); if (typeof opts.onData === 'function') { peer.on('data', (message) => { opts.onData(sock, peer, message); }); } const _onClose = (typeof opts.onClose === 'function') ? opts.onClose : () => {}; const _onError = (typeof opts.onError === 'function') ? opts.onError : () => {}; const _onConnect = (typeof opts.onConnect === 'function') ? opts.onConnect : () => {}; function onClose() { fastify.log.info({id: sock.id}, `peer closed`); _onClose(sock, peer); sock.disconnect(true); peer.destroy(); } function onError(err) { fastify.log.warn({id: sock.id, err}, `peer error`); _onError(sock, peer, err); sock.disconnect(true); peer.destroy(err); } function onConnect() { fastify.log.info({id: sock.id}, `peer connected`); _onConnect(sock, peer); } } });
0
rapidsai_public_repos/node/modules/demo/ssr/graph/plugins
rapidsai_public_repos/node/modules/demo/ssr/graph/plugins/graph/index.js
// Copyright (c) 2021-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. const wrtc = require('wrtc'); const {MemoryView} = require('@rapidsai/cuda'); const {Float32Buffer} = require('@rapidsai/cuda'); const {Graph} = require('@rapidsai/cugraph'); const {Series, Int32} = require('@rapidsai/cudf'); const {loadNodes, loadEdges} = require('./loader'); const {RenderCluster} = require('../../render/cluster'); const {create: shmCreate, detach: shmDetach} = require('shm-typed-array'); module.exports = graphSSRClients; module.exports.graphs = Symbol('graphs'); module.exports.clients = Symbol('clients'); /** * * @param {import('fastify').FastifyInstance} fastify */ function graphSSRClients(fastify) { const graphs = Object.create(null); const clients = Object.create(null); fastify.decorate(module.exports.graphs, graphs); fastify.decorate(module.exports.clients, clients); setInterval(layoutAndRenderGraphs(clients)); return {onConnect, onData, onClose, onError: onClose}; async function onConnect(sock, peer) { const { width = 800, height = 600, layout = true, g: graphId = 'default', } = sock?.handshake?.query || {}; const stream = new wrtc.MediaStream({id: `${sock.id}:video`}); const source = new wrtc.nonstandard.RTCVideoSource({}); clients[stream.id] = { video: source, state: {}, event: {}, props: {width, height, layout}, graph: await loadGraph(graphId), frame: shmCreate(width * height * 3 / 2), peer: peer, }; if (clients[stream.id].graph.dataframes[0]) { const res = getPaginatedRows(clients[stream.id].graph.dataframes[0]); const data = {nodes: {data: res, length: clients[stream.id].graph.dataframes[0].numRows}}; peer.send(JSON.stringify({type: 'data', data})); } if (clients[stream.id].graph.dataframes[1]) { const res = getPaginatedRows(clients[stream.id].graph.dataframes[1]); const data = {edges: {data: res, length: clients[stream.id].graph.dataframes[1].numRows}}; peer.send(JSON.stringify({type: 'data', data})); } stream.addTrack(source.createTrack()); peer.streams.push(stream); peer.addStream(stream); } function onData(sock, peer, message) { const [stream] = peer?.streams || []; if (stream && !peer.destroyed && !peer.destroying) { const {type, data} = (() => { try { return JSON.parse('' + message); } catch (e) { return {}; } })(); switch (data && type) { case 'event': { clients[stream.id].event[data.type] = data; break; } case 'layout': { clients[stream.id].props.layout = JSON.parse(data); break; } } } } function onClose(sock, peer) { const [stream] = peer?.streams || []; if (stream) { delete clients[stream.id]; } const {g: graphId = 'default'} = sock?.handshake?.query || {}; if (graphId in graphs) { if ((graphs[graphId].refCount -= 1) === 0) { // delete graphs[graphId]; } } } async function loadGraph(id) { if (!(id in graphs)) { const asDeviceMemory = (buf) => new (buf[Symbol.species])(buf); const [nodes, edges] = await Promise.all([loadNodes(id), loadEdges(id)]); const src = edges.get('src'); const dst = edges.get('dst'); const graph = Graph.fromEdgeList(src, dst); const positions = new Float32Buffer(Array.from( {length: graph.numNodes * 2}, () => Math.random() * 1000 * (Math.random() < 0.5 ? -1 : 1), )); graphs[id] = { refCount: 0, dataframes: [nodes, edges], graph, nodes: { positions, nodeRadius: asDeviceMemory(nodes.get('size').data), nodeFillColors: asDeviceMemory(nodes.get('color').data), nodeElementIndices: asDeviceMemory(nodes.get('id').data), }, edges: { edgeList: asDeviceMemory(edges.get('edge').data), edgeColors: asDeviceMemory(edges.get('color').data), edgeBundles: asDeviceMemory(edges.get('bundle').data), }, }; } ++graphs[id].refCount; return { gravity: 1.0, linLogMode: false, scalingRatio: 5.0, barnesHutTheta: 0.0, jitterTolerance: 0.05, strongGravityMode: false, outboundAttraction: false, graph: graphs[id].graph, dataframes: graphs[id].dataframes, nodes: {...graphs[id].nodes, length: graphs[id].graph.numNodes}, edges: {...graphs[id].edges, length: graphs[id].graph.numEdges}, }; } } function layoutAndRenderGraphs(clients) { const renderer = new RenderCluster({numWorkers: 1 && 4}); return () => { for (const id in clients) { const client = clients[id]; const sendToClient = (nodes, edges) => { client.peer.send(JSON.stringify({ type: 'data', data: { nodes: {data: getPaginatedRows(nodes), length: nodes.numRows}, edges: {data: getPaginatedRows(edges), length: edges.numRows}, } })); }; if (client.isRendering) { continue; } const state = {...client.state}; const props = {...client.props}; const event = [ 'focus', 'blur', 'keydown', 'keypress', 'keyup', 'mouseenter', 'mousedown', 'mousemove', 'mouseup', 'mouseleave', 'wheel', 'beforeunload', 'shiftKey', 'dragStart', 'dragOver' ].map((x) => client.event[x]) .filter(Boolean); if (event.length === 0 && !props.layout) { continue; } if (event.length !== 0) { client.event = Object.create(null); } if (props.layout == true) { client.graph = forceAtlas2(client.graph); } const { width = client.props.width ?? 800, height = client.props.height ?? 600, } = client.state; state.window = {width: width, height: height, ...client.state.window}; if (client.frame?.byteLength !== (width * height * 3 / 2)) { shmDetach(client.frame.key, true); client.frame = shmCreate(width * height * 3 / 2); } client.isRendering = true; renderer.render(id, { state, props, event, frame: client.frame.key, graph: { ...client.graph, graph: undefined, edges: getIpcHandles(client.graph.edges), nodes: getIpcHandles(client.graph.nodes), }, }, (error, result) => { client.isRendering = false; if (error) { throw error; } const selectedNodes0 = client?.state?.deck?.props?.selectedNodes || []; const selectedNodes1 = result?.state?.deck?.props?.selectedNodes || []; const selectedEdges0 = client?.state?.deck?.props?.selectedEdges || []; const selectedEdges1 = result?.state?.deck?.props?.selectedEdges || []; if ((selectedNodes1.length !== selectedNodes0.length || !selectedNodes1.every((x, i) => x === selectedNodes0[i])) || (selectedEdges1.length !== selectedEdges0.length || !selectedEdges1.every((x, i) => x === selectedEdges0[i]))) { // If selections updated const nodes = Series.new({type: new Int32, data: selectedNodes1}); const edges = Series.new({type: new Int32, data: selectedEdges1}); if (client.graph.dataframes.every((x) => x)) { sendToClient(client.graph.dataframes[0].gather(nodes), client.graph.dataframes[1].gather(edges)); } } // copy result state to client's current state Object.assign(client.state, result?.state || {}); client.video.onFrame({...result.frame, data: client.frame.buffer}); }); } } } function getPaginatedRows(df, page = 1, rowsPerPage = 400) { if (!df) { return {}; } return df.select(['id', 'name']).head(page * rowsPerPage).tail(rowsPerPage).toArrow().toArray(); } function forceAtlas2({graph, nodes, edges, ...params}) { graph.forceAtlas2({...params, positions: nodes.positions}); return { graph, ...params, nodes: {...nodes, length: graph.numNodes}, edges: {...edges, length: graph.numEdges}, }; } function getIpcHandles(obj) { const res = {}; for (const key in obj) { const val = obj[key]; res[key] = val; if (val && (val instanceof MemoryView)) { // try { res[key] = val.getIpcHandle().toJSON(); } catch (e) { throw new Error([ `Failed to get IPC handle for "${key}" buffer`, ...(e || '').toString().split('\n').map((x) => `\t${x}`) ].join('\n')); } } } return res; }
0
rapidsai_public_repos/node/modules/demo/ssr/graph/plugins
rapidsai_public_repos/node/modules/demo/ssr/graph/plugins/graph/loader.js
const {DataFrame, Series, Int32, Uint32, Uint64, Uint8} = require('@rapidsai/cudf'); function loadNodes(graphId) { if (graphId === 'default') { return getDefaultNodes(); } return getDefaultNodes(); } function loadEdges(graphId) { if (graphId === 'default') { return getDefaultEdges(); } return getDefaultEdges(); } module.exports.loadNodes = loadNodes; module.exports.loadEdges = loadEdges; function getDefaultNodes() { return new DataFrame({ name: Series.new([ 'bool::False', 'bool::True', 'char::a', 'char::b', 'char::c', 'char::d', 'colors::1', 'colors::2', 'date::2018-01-01 00:00:00.000000000', 'date_str::2018-01-01 00:00:00', 'date_str::2018-01-02 00:00:00', 'date_str::2018-01-03 00:00:00', 'date_str::2018-01-05 00:00:00', 'dst::0', 'dst::1', 'dst::2', 'dst::3', 'emoji::😋', 'emoji::😋😋', 'int::0', 'int::1', 'int::2', 'int::3', 'num::0.5', 'num::1.5', 'num::2.5', 'num::3.5', 'src::0', 'src::1', 'src::2', 'src::3', 'str::a', 'str::b', 'str::c', 'str::d', 'time::2018-01-05 00:00:00.000000000', 'ustr::a', 'ustr::b', 'ustr::c', 'ustr::d' ]), id: Series.sequence({type: new Uint32, init: 0, step: 1, size: 40}), color: Series.new({ type: new Uint32, data: [ 4293326232, 4294815329, 4294208835, 4294967231, 4293326232, 4294967231, 4281501885, 4294208835, 4292165199, 4284924581, 4281501885, 4281501885, 4294967231, 4294967231, 4281501885, 4289453476, 4281501885, 4294208835, 4289453476, 4281501885, 4289453476, 4289453476, 4294967231, 4281501885, 4293326232, 4281501885, 4294967231, 4294208835, 4289453476, 4294967231, 4294967231, 4294893707, 4294967231, 4281501885, 4294967231, 4284924581, 4294893707, 4294967231, 4294893707, 4294893707 ] }), size: Series.new({ type: new Uint8, data: [ 1, 170, 1, 1, 1, 1, 85, 85, 255, 1, 1, 1, 1, 1, 1, 1, 1, 170, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 255, 1, 1, 1, 1 ] }), }); } function getDefaultEdges() { return new DataFrame({ name: Series.new(Array.from({length: 312}, (_, i) => `${i}`)), src: Series.new({ type: new Int32, data: [ 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 2, 3, 4, 5, 2, 3, 4, 5, 2, 3, 4, 5, 2, 3, 4, 5, 2, 3, 4, 5, 2, 3, 4, 5, 2, 3, 4, 5, 2, 3, 4, 5, 2, 3, 4, 5, 2, 3, 4, 5, 2, 3, 4, 5, 6, 6, 7, 7, 6, 6, 7, 7, 6, 6, 7, 7, 6, 6, 7, 7, 6, 6, 7, 7, 6, 6, 7, 7, 6, 6, 7, 7, 6, 6, 7, 7, 6, 6, 7, 7, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 10, 11, 12, 9, 10, 11, 12, 9, 10, 11, 12, 9, 10, 11, 12, 9, 10, 11, 12, 9, 10, 11, 12, 9, 10, 11, 12, 9, 10, 11, 12, 14, 15, 16, 13, 14, 15, 16, 13, 14, 15, 16, 13, 14, 15, 16, 13, 14, 15, 16, 13, 14, 15, 16, 13, 14, 15, 16, 13, 17, 18, 17, 17, 17, 18, 17, 17, 17, 18, 17, 17, 17, 18, 17, 17, 17, 18, 17, 17, 17, 18, 17, 17, 19, 20, 21, 22, 19, 20, 21, 22, 19, 20, 21, 22, 19, 20, 21, 22, 19, 20, 21, 22, 23, 24, 25, 26, 23, 24, 25, 26, 23, 24, 25, 26, 23, 24, 25, 26, 27, 28, 29, 30, 27, 28, 29, 30, 27, 28, 29, 30, 31, 32, 33, 34, 31, 32, 33, 34, 35, 35, 35, 35 ] }), dst: Series.new({ type: new Int32, data: [ 2, 3, 4, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 10, 11, 12, 14, 15, 16, 13, 17, 18, 17, 17, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 35, 35, 35, 36, 37, 38, 39, 6, 6, 7, 7, 8, 8, 8, 8, 9, 10, 11, 12, 14, 15, 16, 13, 17, 18, 17, 17, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 35, 35, 35, 36, 37, 38, 39, 8, 8, 8, 8, 9, 10, 11, 12, 14, 15, 16, 13, 17, 18, 17, 17, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 35, 35, 35, 36, 37, 38, 39, 9, 10, 11, 12, 14, 15, 16, 13, 17, 18, 17, 17, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 35, 35, 35, 36, 37, 38, 39, 14, 15, 16, 13, 17, 18, 17, 17, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 35, 35, 35, 36, 37, 38, 39, 17, 18, 17, 17, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 35, 35, 35, 36, 37, 38, 39, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 35, 35, 35, 36, 37, 38, 39, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 35, 35, 35, 36, 37, 38, 39, 27, 28, 29, 30, 31, 32, 33, 34, 35, 35, 35, 35, 36, 37, 38, 39, 31, 32, 33, 34, 35, 35, 35, 35, 36, 37, 38, 39, 35, 35, 35, 35, 36, 37, 38, 39, 36, 37, 38, 39 ] }), edge: Series.new({ type: new Uint64, data: [ 8589934593n, 12884901888n, 17179869185n, 21474836481n, 25769803777n, 25769803776n, 30064771073n, 30064771073n, 34359738369n, 34359738368n, 34359738369n, 34359738369n, 38654705665n, 42949672960n, 47244640257n, 51539607553n, 60129542145n, 64424509440n, 68719476737n, 55834574849n, 73014444033n, 77309411328n, 73014444033n, 73014444033n, 81604378625n, 85899345920n, 90194313217n, 94489280513n, 98784247809n, 103079215104n, 107374182401n, 111669149697n, 115964116993n, 120259084288n, 124554051585n, 128849018881n, 133143986177n, 137438953472n, 141733920769n, 146028888065n, 150323855361n, 150323855360n, 150323855361n, 150323855361n, 154618822657n, 158913789952n, 163208757249n, 167503724545n, 25769803778n, 25769803779n, 30064771076n, 30064771077n, 34359738370n, 34359738371n, 34359738372n, 34359738373n, 38654705666n, 42949672963n, 47244640260n, 51539607557n, 60129542146n, 64424509443n, 68719476740n, 55834574853n, 73014444034n, 77309411331n, 73014444036n, 73014444037n, 81604378626n, 85899345923n, 90194313220n, 94489280517n, 98784247810n, 103079215107n, 107374182404n, 111669149701n, 115964116994n, 120259084291n, 124554051588n, 128849018885n, 133143986178n, 137438953475n, 141733920772n, 146028888069n, 150323855362n, 150323855363n, 150323855364n, 150323855365n, 154618822658n, 158913789955n, 163208757252n, 167503724549n, 34359738374n, 34359738374n, 34359738375n, 34359738375n, 38654705670n, 42949672966n, 47244640263n, 51539607559n, 60129542150n, 64424509446n, 68719476743n, 55834574855n, 73014444038n, 77309411334n, 73014444039n, 73014444039n, 81604378630n, 85899345926n, 90194313223n, 94489280519n, 98784247814n, 103079215110n, 107374182407n, 111669149703n, 115964116998n, 120259084294n, 124554051591n, 128849018887n, 133143986182n, 137438953478n, 141733920775n, 146028888071n, 150323855366n, 150323855366n, 150323855367n, 150323855367n, 154618822662n, 158913789958n, 163208757255n, 167503724551n, 38654705672n, 42949672968n, 47244640264n, 51539607560n, 60129542152n, 64424509448n, 68719476744n, 55834574856n, 73014444040n, 77309411336n, 73014444040n, 73014444040n, 81604378632n, 85899345928n, 90194313224n, 94489280520n, 98784247816n, 103079215112n, 107374182408n, 111669149704n, 115964117000n, 120259084296n, 124554051592n, 128849018888n, 133143986184n, 137438953480n, 141733920776n, 146028888072n, 150323855368n, 150323855368n, 150323855368n, 150323855368n, 154618822664n, 158913789960n, 163208757256n, 167503724552n, 60129542153n, 64424509450n, 68719476747n, 55834574860n, 73014444041n, 77309411338n, 73014444043n, 73014444044n, 81604378633n, 85899345930n, 90194313227n, 94489280524n, 98784247817n, 103079215114n, 107374182411n, 111669149708n, 115964117001n, 120259084298n, 124554051595n, 128849018892n, 133143986185n, 137438953482n, 141733920779n, 146028888076n, 150323855369n, 150323855370n, 150323855371n, 150323855372n, 154618822665n, 158913789962n, 163208757259n, 167503724556n, 73014444046n, 77309411343n, 73014444048n, 73014444045n, 81604378638n, 85899345935n, 90194313232n, 94489280525n, 98784247822n, 103079215119n, 107374182416n, 111669149709n, 115964117006n, 120259084303n, 124554051600n, 128849018893n, 133143986190n, 137438953487n, 141733920784n, 146028888077n, 150323855374n, 150323855375n, 150323855376n, 150323855373n, 154618822670n, 158913789967n, 163208757264n, 167503724557n, 81604378641n, 85899345938n, 90194313233n, 94489280529n, 98784247825n, 103079215122n, 107374182417n, 111669149713n, 115964117009n, 120259084306n, 124554051601n, 128849018897n, 133143986193n, 137438953490n, 141733920785n, 146028888081n, 150323855377n, 150323855378n, 150323855377n, 150323855377n, 154618822673n, 158913789970n, 163208757265n, 167503724561n, 98784247827n, 103079215124n, 107374182421n, 111669149718n, 115964117011n, 120259084308n, 124554051605n, 128849018902n, 133143986195n, 137438953492n, 141733920789n, 146028888086n, 150323855379n, 150323855380n, 150323855381n, 150323855382n, 154618822675n, 158913789972n, 163208757269n, 167503724566n, 115964117015n, 120259084312n, 124554051609n, 128849018906n, 133143986199n, 137438953496n, 141733920793n, 146028888090n, 150323855383n, 150323855384n, 150323855385n, 150323855386n, 154618822679n, 158913789976n, 163208757273n, 167503724570n, 133143986203n, 137438953500n, 141733920797n, 146028888094n, 150323855387n, 150323855388n, 150323855389n, 150323855390n, 154618822683n, 158913789980n, 163208757277n, 167503724574n, 150323855391n, 150323855392n, 150323855393n, 150323855394n, 154618822687n, 158913789984n, 163208757281n, 167503724578n, 154618822691n, 158913789987n, 163208757283n, 167503724579n ] }), color: Series.new({ type: new Uint64, data: [ 18443486512814075489n, 18446743798830003608n, 18439695761793724001n, 18446743798831492705n, 18388910578132168289n, 18388910578130679192n, 18443486512814075489n, 18443486512814075489n, 18434709163029147233n, 18434709163027658136n, 18434709163029147233n, 18434709163029147233n, 18403610945516318305n, 18388910578130679192n, 18388910578132168289n, 18446743798831492705n, 18388910578132168289n, 18423062401426847128n, 18388910578132168289n, 18446743798831492705n, 18443486512814075489n, 18423062401426847128n, 18443486512814075489n, 18443486512814075489n, 18388910578132168289n, 18423062401426847128n, 18423062401428336225n, 18446743798831492705n, 18388910578132168289n, 18439695761792234904n, 18388910578132168289n, 18446743798831492705n, 18443486512814075489n, 18423062401426847128n, 18446743798831492705n, 18446743798831492705n, 18446428015656021601n, 18446743798830003608n, 18388910578132168289n, 18446743798831492705n, 18403610945516318305n, 18403610945514829208n, 18403610945516318305n, 18403610945516318305n, 18446428015656021601n, 18446743798830003608n, 18446428015656021601n, 18446428015656021601n, 18388910578131561795n, 18388910578132320191n, 18443486512812586392n, 18443486512814227391n, 18434709163028540739n, 18434709163029299135n, 18434709163027658136n, 18434709163029299135n, 18403610945515711811n, 18388910578132320191n, 18388910578130679192n, 18446743798831644607n, 18388910578131561795n, 18423062401428488127n, 18388910578130679192n, 18446743798831644607n, 18443486512813468995n, 18423062401428488127n, 18443486512812586392n, 18443486512814227391n, 18388910578131561795n, 18423062401428488127n, 18423062401426847128n, 18446743798831644607n, 18388910578131561795n, 18439695761793875903n, 18388910578130679192n, 18446743798831644607n, 18443486512813468995n, 18423062401428488127n, 18446743798830003608n, 18446743798831644607n, 18446428015655415107n, 18446743798831644607n, 18388910578130679192n, 18446743798831644607n, 18403610945515711811n, 18403610945516470207n, 18403610945514829208n, 18403610945516470207n, 18446428015655415107n, 18446743798831644607n, 18446428015654532504n, 18446428015656173503n, 18434709163015833789n, 18434709163015833789n, 18434709163028540739n, 18434709163028540739n, 18403610945503004861n, 18388910578118854845n, 18388910578131561795n, 18446743798830886211n, 18388910578118854845n, 18423062401415022781n, 18388910578131561795n, 18446743798830886211n, 18443486512800762045n, 18423062401415022781n, 18443486512813468995n, 18443486512813468995n, 18388910578118854845n, 18423062401415022781n, 18423062401427729731n, 18446743798830886211n, 18388910578118854845n, 18439695761780410557n, 18388910578131561795n, 18446743798830886211n, 18443486512800762045n, 18423062401415022781n, 18446743798830886211n, 18446743798830886211n, 18446428015642708157n, 18446743798818179261n, 18388910578131561795n, 18446743798830886211n, 18403610945503004861n, 18403610945503004861n, 18403610945515711811n, 18403610945515711811n, 18446428015642708157n, 18446743798818179261n, 18446428015655415107n, 18446428015655415107n, 18403610945513668175n, 18388910578129518159n, 18388910578129518159n, 18446743798828842575n, 18388910578129518159n, 18423062401425686095n, 18388910578129518159n, 18446743798828842575n, 18443486512811425359n, 18423062401425686095n, 18443486512811425359n, 18443486512811425359n, 18388910578129518159n, 18423062401425686095n, 18423062401425686095n, 18446743798828842575n, 18388910578129518159n, 18439695761791073871n, 18388910578129518159n, 18446743798828842575n, 18443486512811425359n, 18423062401425686095n, 18446743798828842575n, 18446743798828842575n, 18446428015653371471n, 18446743798828842575n, 18388910578129518159n, 18446743798828842575n, 18403610945513668175n, 18403610945513668175n, 18403610945513668175n, 18403610945513668175n, 18446428015653371471n, 18446743798828842575n, 18446428015653371471n, 18446428015653371471n, 18388910578122277541n, 18423062401415022781n, 18388910578118854845n, 18446743798831644607n, 18443486512804184741n, 18423062401415022781n, 18443486512800762045n, 18443486512814227391n, 18388910578122277541n, 18423062401415022781n, 18423062401415022781n, 18446743798831644607n, 18388910578122277541n, 18439695761780410557n, 18388910578118854845n, 18446743798831644607n, 18443486512804184741n, 18423062401415022781n, 18446743798818179261n, 18446743798831644607n, 18446428015646130853n, 18446743798818179261n, 18388910578118854845n, 18446743798831644607n, 18403610945506427557n, 18403610945503004861n, 18403610945503004861n, 18403610945516470207n, 18446428015646130853n, 18446743798818179261n, 18446428015642708157n, 18446428015656173503n, 18443486512800762045n, 18423062401422974372n, 18443486512800762045n, 18443486512814227391n, 18388910578118854845n, 18423062401422974372n, 18423062401415022781n, 18446743798831644607n, 18388910578118854845n, 18439695761788362148n, 18388910578118854845n, 18446743798831644607n, 18443486512800762045n, 18423062401422974372n, 18446743798818179261n, 18446743798831644607n, 18446428015642708157n, 18446743798826130852n, 18388910578118854845n, 18446743798831644607n, 18403610945503004861n, 18403610945510956452n, 18403610945503004861n, 18403610945516470207n, 18446428015642708157n, 18446743798826130852n, 18446428015642708157n, 18446428015656173503n, 18388910578131561795n, 18423062401422974372n, 18423062401427729731n, 18446743798830886211n, 18388910578131561795n, 18439695761788362148n, 18388910578131561795n, 18446743798830886211n, 18443486512813468995n, 18423062401422974372n, 18446743798830886211n, 18446743798830886211n, 18446428015655415107n, 18446743798826130852n, 18388910578131561795n, 18446743798830886211n, 18403610945515711811n, 18403610945510956452n, 18403610945515711811n, 18403610945515711811n, 18446428015655415107n, 18446743798826130852n, 18446428015655415107n, 18446428015655415107n, 18388910578118854845n, 18439695761788362148n, 18388910578126806436n, 18446743798831644607n, 18443486512800762045n, 18423062401422974372n, 18446743798826130852n, 18446743798831644607n, 18446428015642708157n, 18446743798826130852n, 18388910578126806436n, 18446743798831644607n, 18403610945503004861n, 18403610945510956452n, 18403610945510956452n, 18403610945516470207n, 18446428015642708157n, 18446743798826130852n, 18446428015650659748n, 18446428015656173503n, 18443486512800762045n, 18423062401426847128n, 18446743798818179261n, 18446743798831644607n, 18446428015642708157n, 18446743798830003608n, 18388910578118854845n, 18446743798831644607n, 18403610945503004861n, 18403610945514829208n, 18403610945503004861n, 18403610945516470207n, 18446428015642708157n, 18446743798830003608n, 18446428015642708157n, 18446428015656173503n, 18446428015655415107n, 18446743798826130852n, 18388910578132320191n, 18446743798831644607n, 18403610945515711811n, 18403610945510956452n, 18403610945516470207n, 18403610945516470207n, 18446428015655415107n, 18446743798826130852n, 18446428015656173503n, 18446428015656173503n, 18403610945516396683n, 18403610945516470207n, 18403610945503004861n, 18403610945516470207n, 18446428015656099979n, 18446743798831644607n, 18446428015642708157n, 18446428015656173503n, 18446428015646130853n, 18446743798821601957n, 18446428015646130853n, 18446428015646130853n ] }), bundle: Series.new({ type: new Uint64, data: [ 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 8589934592n, 8589934593n, 12884901888n, 4294967296n, 12884901889n, 12884901890n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 12884901890n, 4294967296n, 12884901888n, 12884901889n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 12884901888n, 4294967296n, 12884901889n, 12884901890n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 8589934592n, 8589934593n, 8589934593n, 8589934592n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 8589934592n, 8589934593n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 8589934592n, 8589934593n, 8589934592n, 8589934593n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 12884901888n, 4294967296n, 12884901889n, 12884901890n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 17179869184n, 17179869185n, 17179869186n, 17179869187n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 12884901888n, 4294967296n, 12884901889n, 12884901890n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n, 4294967296n ] }) }); }
0
rapidsai_public_repos/node/modules/demo/ssr/graph
rapidsai_public_repos/node/modules/demo/ssr/graph/public/video.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>WebRTC NVENC Demo</title> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="theme-color" content="#2e2e2e" /> </head> <body style="background:#2e2e2e; margin:0;"> <video autoplay muted width="800" height="600"></video> <script src="https://cdn.jsdelivr.net/npm/[email protected]/simplepeer.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.1.3/socket.io.js"></script> <script> const sock = io({ reconnection: true, transports: ['websocket'], query: { g: Math.floor(Math.random() * 1e10) } }); const video = document.querySelector('video'); const peer = new SimplePeer({ trickle: true, initiator: true, sdpTransform: (sdp) => { // Remove bandwidth restrictions // https://github.com/webrtc/samples/blob/89f17a83ed299ef28d45b933419d809b93d41759/src/content/peerconnection/bandwidth/js/main.js#L240 sdp = sdp.replace(/b=AS:.*\r\n/, '').replace(/b=TIAS:.*\r\n/, ''); // Force h264 encoding by removing all VP8/9 codecs from the sdp sdp = onlyH264(sdp); return sdp; } }); // Negotiate handshake sock.on('signal', (data) => peer.signal(data)); peer.on('signal', (data) => sock.emit('signal', data)); peer.on('data', (data) => { var decoded = new TextDecoder().decode(data); var decodedjson = JSON.parse(decoded); console.log("got data from peer: ", decodedjson.data); }); // Server video stream peer.on('stream', (stream) => { ('srcObject' in video) ? (video.srcObject = stream) : (video.src = window.URL.createObjectURL(stream)); // for older browsers video.play(); }); dispatchRemoteEvent(video, 'blur'); dispatchRemoteEvent(video, 'focus'); dispatchRemoteEvent(video, 'wheel'); dispatchRemoteEvent(window, 'beforeunload'); dispatchRemoteEvent(document, 'keyup'); dispatchRemoteEvent(document, 'keydown'); dispatchRemoteEvent(document, 'keypress'); dispatchRemoteEvent(video, 'mouseup'); dispatchRemoteEvent(video, 'mousemove'); dispatchRemoteEvent(video, 'mousedown'); dispatchRemoteEvent(video, 'mouseenter'); dispatchRemoteEvent(video, 'mouseleave'); function dispatchRemoteEvent(target, type) { let timeout = null; target.addEventListener(type, (e) => { if (target === video) { e.preventDefault(); } if (!timeout) { timeout = setTimeout(() => { timeout = null; }, 1000 / 60); peer.send(JSON.stringify({ type: 'event', data: serializeEvent(e) })); } }); } function serializeEvent(original) { return Object .getOwnPropertyNames(Object.getPrototypeOf(original)) .reduce((serialized, field) => { switch (typeof original[field]) { case 'object': case 'symbol': case 'function': break; default: serialized[field] = original[field]; } return serialized; }, { type: original.type }); } function onlyH264(sdp) { // remove non-h264 codecs from the supported codecs list const videos = sdp.match(/^m=video.*$/gm); if (videos) { return videos.map((video) => [video, [ ...getCodecIds(sdp, 'VP9'), ...getCodecIds(sdp, 'VP8'), ...getCodecIds(sdp, 'HEVC'), ...getCodecIds(sdp, 'H265') ]]).reduce((sdp, [video, ids]) => ids.reduce((sdp, id) => [ new RegExp(`^a=fmtp:${id}(.*?)$`, 'gm'), new RegExp(`^a=rtpmap:${id}(.*?)$`, 'gm'), new RegExp(`^a=rtcp-fb:${id}(.*?)$`, 'gm'), ].reduce((sdp, expr) => sdp.replace(expr, ''), sdp), sdp) .replace(video, ids.reduce((video, id) => video.replace(` ${id}`, ''), video)), sdp) .replace('\r\n', '\n').split('\n').map((x) => x.trim()).filter(Boolean).join('\r\n') + '\r\n'; } return sdp; function getCodecIds(sdp, codec) { return getIdsForMatcher(sdp, new RegExp( `^a=rtpmap:(?<id>\\d+)\\s+${codec}\\/\\d+$`, 'm' )).reduce((ids, id) => [ ...ids, id, ...getIdsForMatcher(sdp, new RegExp( `^a=fmtp:(?<id>\\d+)\\s+apt=${id}$`, 'm' )) ], []); } function getIdsForMatcher(sdp, matcher) { const ids = []; /** @type RegExpMatchArray */ let res, str = '' + sdp, pos = 0; for (; res = str.match(matcher); str = str.slice(pos)) { pos = res.index + res[0].length; if (res.groups) { ids.push(res.groups.id); } } return ids; } } </script> </body> </html>
0
rapidsai_public_repos/node/modules/demo/ssr
rapidsai_public_repos/node/modules/demo/ssr/point-cloud/package.json
{ "private": true, "name": "@rapidsai/demo-point-cloud-ssr", "main": "index.js", "version": "22.12.2", "license": "Apache-2.0", "author": "NVIDIA, Inc. (https://nvidia.com/)", "maintainers": [ "Paul Taylor <[email protected]>" ], "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/cuda": "~22.12.2", "@rapidsai/deck.gl": "~22.12.2", "@rapidsai/jsdom": "~22.12.2", "fastify": "3.20.2", "fastify-plugin": "3.0.0", "fastify-socket.io": "2.0.0", "fastify-static": "4.2.3", "nanoid": "3.1.31", "rxjs": "6.6.7", "shm-typed-array": "0.0.16", "simple-peer": "9.11.0", "socket.io": "4.1.3" }, "files": [ "render", "public", "plugins", "index.js", "package.json" ] }
0
rapidsai_public_repos/node/modules/demo/ssr
rapidsai_public_repos/node/modules/demo/ssr/point-cloud/index.js
#!/usr/bin/env -S node --experimental-vm-modules --trace-uncaught // 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. const fastify = require('fastify')(); fastify // .register(require('./plugins/webrtc'), require('./plugins/point-cloud')(fastify)) .register(require('fastify-static'), {root: require('path').join(__dirname, 'public')}) .get('/', (req, reply) => reply.sendFile('video.html')); fastify.listen(8080).then(() => console.log('server ready'));
0
rapidsai_public_repos/node/modules/demo/ssr
rapidsai_public_repos/node/modules/demo/ssr/point-cloud/README.md
# Point Cloud Server Side Rendering (SSR) and Streaming Server The back end to the [Viz-App](https://github.com/rapidsai/node/tree/main/modules/demo/viz-app) demo, using deck.gl for rendering. Streamed using webRTC utilizing [nvENC](https://docs.nvidia.com/video-technologies/video-codec-sdk/nvenc-video-encoder-api-prog-guide/). ## Featured Dependencies - @rapidsai/cudf - @rapidsai/jsdom - @rapidsai/deckgl ## Data Requirements The demo will default to internal data, called `indoor.0.1.laz`. ## Start To start the server: ```bash yarn start #NOTE: For the demo to work, run this in one terminal instance AND run the Viz-App in another terminal (use point cloud option) ```
0
rapidsai_public_repos/node/modules/demo/ssr/point-cloud
rapidsai_public_repos/node/modules/demo/ssr/point-cloud/render/worker.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. const {fromEvent, EMPTY} = require('rxjs'); const {tap, groupBy, mergeMap, concatMap} = require('rxjs/operators'); const {Renderer} = require('./render'); const renderer = new Renderer(); function render({props = {}, state = {}, event = [], frame = 0}) { return renderer.render(props, state, event, frame); } fromEvent(process, 'message', (x) => x) .pipe(groupBy(({type}) => type)) .pipe(mergeMap((group) => { switch (group.key) { case 'exit': return group.pipe(tap(({code}) => process.exit(code))); case 'render.request': return group // .pipe(concatMap(({data}) => render(data), ({id}, data) => ({id, data}))) // .pipe(tap((result) => send({...result, type: 'render.result'}))); } return EMPTY; })) .subscribe(); function send(x) { try { JSON.stringify(x); process.send(x); } catch (e) { debugger; } }
0
rapidsai_public_repos/node/modules/demo/ssr/point-cloud
rapidsai_public_repos/node/modules/demo/ssr/point-cloud/render/render.js
// Copyright (c) 2021-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. const {RapidsJSDOM} = require('@rapidsai/jsdom'); const copyFramebuffer = require('./copy')(); class Renderer { constructor() { const onAnimationFrameRequested = immediateAnimationFrame(this); const jsdom = new RapidsJSDOM({module, onAnimationFrameRequested}); const {deck, render} = jsdom.window.evalFn(makeDeck); this.deck = deck; this.jsdom = jsdom; this._render = render; } async render(props = {}, state = {}, events = [], frame = 0) { const window = this.jsdom.window; props && this.deck.setProps(props); state?.deck && this.deck.restore(state.deck); state?.window && Object.assign(window, state.window); (events || []).forEach((event) => window.dispatchEvent(event)); await this._render(); const deck = this.deck.serialize(); return { frame: copyFramebuffer(this.deck.animationLoop, frame), state: { deck: { ...deck, props: { ...deck.props, transitionDuration: 0, } }, window: { x: window.x, y: window.y, title: window.title, width: window.width, height: window.height, cursor: window.cursor, mouseX: window.mouseX, mouseY: window.mouseY, buttons: window.buttons, scrollX: window.scrollX, scrollY: window.scrollY, modifiers: window.modifiers, mouseInWindow: window.mouseInWindow, }, } }; } } module.exports.Renderer = Renderer; function immediateAnimationFrame(renderer) { let request = null; let flushing = false; const flush = () => { flushing = true; while (request && request.active) { const f = request.flush; request = null; f(); } flushing = false; }; return (r) => { if (flushing) { return request = r; } if (renderer?.deck?.animationLoop?._initialized) { // return flush(request = r); } if (!request && (request = r)) { setImmediate(flush); } }; } function makeDeck() { const {log: deckLog} = require('@deck.gl/core'); deckLog.level = 0; deckLog.enable(false); const {OrbitView, COORDINATE_SYSTEM} = require('@deck.gl/core'); const {PointCloudLayer} = require('@deck.gl/layers'); const {DeckSSR} = require('@rapidsai/deck.gl'); const {LASLoader} = require('@loaders.gl/las'); const {registerLoaders} = require('@loaders.gl/core'); LASLoader.worker = false; registerLoaders(LASLoader); // Data source: kaarta.com const LAZ_SAMPLE = 'http://localhost:8080/indoor.0.1.laz'; const makeLayers = (deck) => { return [ new PointCloudLayer({ id: 'laz-point-cloud-layer', data: LAZ_SAMPLE, coordinateSystem: COORDINATE_SYSTEM.CARTESIAN, getNormal: [0, 1, 0], getColor: [255, 255, 255], opacity: 0.5, pointSize: 0.5 }), ] }; const deck = new DeckSSR({ _sync: true, createFramebuffer: true, initialViewState: { target: [0, 0, 0], rotationX: 0, rotationOrbit: 0, orbitAxis: 'Y', fov: 50, minZoom: 0, maxZoom: 10, zoom: 1 }, layers: makeLayers(null), views: [ new OrbitView(), ], controller: true, transitionDuration: 0, parameters: {clearColor: [0.93, 0.86, 0.81, 1]}, onAfterAnimationFrameRender({_loop}) { _loop.pause(); }, }); return { deck, render() { const done = deck.animationLoop.waitForRender(); deck.setProps({layers: makeLayers(deck)}); deck.animationLoop.start(); return done; }, }; }
0
rapidsai_public_repos/node/modules/demo/ssr/point-cloud
rapidsai_public_repos/node/modules/demo/ssr/point-cloud/render/cluster.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. const workerPath = require('path').join(__dirname, 'worker.js'); class RenderCluster { constructor({fps = 60, numWorkers = 4} = {}) { this._fps = fps; this._timerId = null; this._workerId = 0; this._reqs = Object.create(null); this._jobs = Object.create(null); this._workers = this._createWorkers(numWorkers); process.on('exit', killWorkers); process.on('beforeExit', killWorkers); function killWorkers(code = 'SIGKILL') { this._workers.forEach((worker) => { if (!worker.killed) { worker.send({type: 'exit', code}); worker.kill(code); } }); } } pause() { if (this._timerId !== null) { clearInterval(this._timerId); this._timerId = null; } } start() { if (this._timerId === null) { this._timerId = setInterval(() => this.flush(), 1000 / this._fps); } } render(id, data, callback) { const request = this._reqs[id] || (this._reqs[id] = Object.create(null)); (request.callbacks || (request.callbacks = [])).push(callback); request.data || (request.data = Object.create(null)); Object.assign(request.data, data); this.start(); } flush() { const requests = this._reqs; this._reqs = Object.create(null); const workers = this._workers.slice().sort((a, b) => a.jobs - b.jobs); for (const id in requests) { if (!(id in this._jobs)) { this._jobs[id] = dispatchJob(id, requests, workers[this._workerId]); this._workerId = (this._workerId + 1) % workers.length; } } } _onWorkerExit(workerId, ...xs) { console.log(`worker ${workerId} exit`, ...xs); } _onWorkerError(workerId, ...xs) { console.log(`worker ${workerId} error`, ...xs); } _onWorkerClose(workerId, ...xs) { console.log(`worker ${workerId} close`, ...xs); } _onWorkerDisconnect(workerId, ...xs) { console.log(`worker ${workerId} disconnect`, ...xs); } _onWorkerMessage(_workerId, {id, type, data}) { switch (type) { case 'render.result': const p = this._jobs[id]; delete this._jobs[id]; return p && p.resolve(data); } } _createWorkers(numWorkers = 4) { return Array.from({length: numWorkers}).map((_, i) => { const worker = require('child_process').fork(workerPath, { cwd: __dirname, // serialization: 'advanced', execArgv: ['--trace-uncaught'], stdio: ['pipe', 'inherit', 'inherit', 'ipc'], env: { ...process.env, DISPLAY: undefined, WORKER_ID: i, NUM_WORKERS: numWorkers, }, }); worker.jobs = 0; return worker.on('exit', this._onWorkerExit.bind(this, i)) .on('error', this._onWorkerError.bind(this, i)) .on('close', this._onWorkerClose.bind(this, i)) .on('message', this._onWorkerMessage.bind(this, i)) .on('disconnect', this._onWorkerDisconnect.bind(this, i)); }); } } function dispatchJob(id, requests, worker) { const {promise, resolve, reject} = promiseSubject(); promise .catch((err) => { if (id in requests) { --worker.jobs; const {callbacks} = requests[id]; delete requests[id]; callbacks.forEach((cb) => cb(err, null)); } }) .then((data) => { if (id in requests) { --worker.jobs; const {callbacks} = requests[id]; delete requests[id]; callbacks.forEach((cb) => cb(null, data)); } }); const data = {...requests[id].data}; ++worker.jobs; worker.send({id, type: 'render.request', data}); return {promise, resolve, reject}; } function promiseSubject() { let resolve, reject; let promise = new Promise((r1, r2) => { resolve = r1; reject = r2; }); return {promise, resolve, reject}; } module.exports.RenderCluster = RenderCluster;
0
rapidsai_public_repos/node/modules/demo/ssr/point-cloud
rapidsai_public_repos/node/modules/demo/ssr/point-cloud/render/copy.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. const {CUDA, Uint8Buffer} = require('@rapidsai/cuda'); const {Buffer: DeckBuffer} = require('@rapidsai/deck.gl'); const {Framebuffer, readPixelsToBuffer} = require('@luma.gl/webgl'); const shm = require('shm-typed-array'); Object.defineProperty(Framebuffer, Symbol.hasInstance, { value: (x) => x?.constructor?.name === 'Framebuffer', }); module.exports = copyAndConvertFramebuffer; function copyAndConvertFramebuffer() { let i420DeviceBuffer = null; let rgbaDeviceBuffer = null; return ({gl, framebuffer}, sharedMemoryKey) => { const {width, height} = framebuffer; const rgbaByteLength = width * height * 4; const i420ByteLength = width * height * 3 / 2; if (rgbaDeviceBuffer?.byteLength !== rgbaByteLength) { rgbaDeviceBuffer?.delete({deleteChildren: true}); rgbaDeviceBuffer = new DeckBuffer(gl, { byteLength: rgbaByteLength, accessor: {type: gl.UNSIGNED_BYTE, size: 4}, }); } if (i420DeviceBuffer?.byteLength !== i420ByteLength) { i420DeviceBuffer = new Uint8Buffer(i420ByteLength); } // DtoD copy from framebuffer into our pixelbuffer readPixelsToBuffer( framebuffer, {sourceType: gl.UNSIGNED_BYTE, sourceFormat: gl.RGBA, target: rgbaDeviceBuffer}); // Map and unmap the GL buffer as a CUDA buffer rgbaDeviceBuffer.asMappedResource((glBuffer) => { const cuBuffer = glBuffer.asCUDABuffer(0, rgbaByteLength); // flip horizontally to account for WebGL's coordinate system (e.g. ffmpeg -vf vflip) CUDA.rgbaMirror(width, height, 0, cuBuffer); // convert colorspace from OpenGL's BGRA to WebRTC's IYUV420 CUDA.bgraToYCrCb420(i420DeviceBuffer, cuBuffer, width, height); }); // DtoH copy for output const out = shm.get(sharedMemoryKey, 'Uint8ClampedArray'); i420DeviceBuffer.copyInto(out); shm.detach(sharedMemoryKey); return {width, height, data: sharedMemoryKey}; }; }
0
rapidsai_public_repos/node/modules/demo/ssr/point-cloud
rapidsai_public_repos/node/modules/demo/ssr/point-cloud/plugins/webrtc.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. const wrtc = require('wrtc'); const Peer = require('simple-peer'); module.exports = require('fastify-plugin')(function(fastify, opts, next) { fastify .register(require('fastify-socket.io')) // .after(() => fastify.io.on('connect', onConnect)); next(); function onConnect(sock) { const peer = new Peer({ wrtc, sdpTransform: (sdp) => { // Remove bandwidth restrictions // https://github.com/webrtc/samples/blob/89f17a83ed299ef28d45b933419d809b93d41759/src/content/peerconnection/bandwidth/js/main.js#L240 sdp = sdp.replace(/b=AS:.*\r\n/, '').replace(/b=TIAS:.*\r\n/, ''); return sdp; } }); peer.on('close', onClose); peer.on('error', onError); peer.on('connect', onConnect); sock.on('disconnect', () => peer.destroy()); // Handle signaling sock.on('signal', (data) => { peer.signal(data); }); peer.on('signal', (data) => { sock.emit('signal', data); }); if (typeof opts.onData === 'function') { peer.on('data', (message) => { opts.onData(sock, peer, message); }); } const _onClose = (typeof opts.onClose === 'function') ? opts.onClose : () => {}; const _onError = (typeof opts.onError === 'function') ? opts.onError : () => {}; const _onConnect = (typeof opts.onConnect === 'function') ? opts.onConnect : () => {}; function onClose() { fastify.log.info({id: sock.id}, `peer closed`); _onClose(sock, peer); sock.disconnect(true); peer.destroy(); } function onError(err) { fastify.log.warn({id: sock.id, err}, `peer error`); _onError(sock, peer, err); sock.disconnect(true); peer.destroy(err); } function onConnect() { fastify.log.info({id: sock.id}, `peer connected`); _onConnect(sock, peer); } } });
0
rapidsai_public_repos/node/modules/demo/ssr/point-cloud/plugins
rapidsai_public_repos/node/modules/demo/ssr/point-cloud/plugins/point-cloud/index.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. const wrtc = require('wrtc'); const {RenderCluster} = require('../../render/cluster'); const {create: shmCreate, detach: shmDetach} = require('shm-typed-array'); module.exports = graphSSRClients; module.exports.clients = Symbol('clients'); /** * * @param {import('fastify').FastifyInstance} fastify */ function graphSSRClients(fastify) { const clients = Object.create(null); fastify.decorate(module.exports.clients, clients); setInterval(layoutAndRenderPointCloud(clients)); return {onConnect, onData, onClose, onError: onClose}; async function onConnect(sock, peer) { const { width = 800, height = 600, layout = true, g: graphId = 'default', } = sock?.handshake?.query || {}; const stream = new wrtc.MediaStream({id: `${sock.id}:video`}); const source = new wrtc.nonstandard.RTCVideoSource({}); clients[stream.id] = { video: source, state: {}, event: {}, props: {width, height, layout}, frame: shmCreate(width * height * 3 / 2), peer: peer, }; stream.addTrack(source.createTrack()); peer.streams.push(stream); peer.addStream(stream); } function onData(sock, peer, message) { const [stream] = peer?.streams || []; if (stream && !peer.destroyed && !peer.destroying) { const {type, data} = (() => { try { return JSON.parse('' + message); } catch (e) { return {}; } })(); switch (data && type) { case 'event': { clients[stream.id].event[data.type] = data; break; } } } } function onClose(sock, peer) { const [stream] = peer?.streams || []; if (stream) { delete clients[stream.id]; } } } function layoutAndRenderPointCloud(clients) { const renderer = new RenderCluster({numWorkers: 1 && 4}); return () => { for (const id in clients) { const client = clients[id]; if (client.isRendering) { continue; } const state = {...client.state}; const props = {...client.props}; const event = [ 'focus', 'blur', 'keydown', 'keypress', 'keyup', 'mouseenter', 'mousedown', 'mousemove', 'mouseup', 'mouseleave', 'wheel', 'beforeunload', 'shiftKey', 'dragStart', 'dragOver' ].map((x) => client.event[x]) .filter(Boolean); if (event.length === 0 && !props.layout) { continue; } if (event.length !== 0) { client.event = Object.create(null); } const { width = client.props.width ?? 800, height = client.props.height ?? 600, } = client.state; state.window = {width: width, height: height, ...client.state.window}; if (client.frame?.byteLength !== (width * height * 3 / 2)) { shmDetach(client.frame.key, true); client.frame = shmCreate(width * height * 3 / 2); } client.isRendering = true; renderer.render(id, { state, props, event, frame: client.frame.key, }, (error, result) => { client.isRendering = false; if (id in clients) { if (error) { throw error; } // copy result state to client's current state result?.state && Object.assign(client.state, result.state); client.video.onFrame({...result.frame, data: client.frame.buffer}); } }); } } }
0
rapidsai_public_repos/node/modules/demo/ssr/point-cloud
rapidsai_public_repos/node/modules/demo/ssr/point-cloud/public/indoor.0.1.laz
version https://git-lfs.github.com/spec/v1 oid sha256:c0fa28e1429c62c62523b3cac8507fda6c0063c431a8a9ce03d8b7d9484fccd5 size 1644721
0
rapidsai_public_repos/node/modules/demo/ssr/point-cloud
rapidsai_public_repos/node/modules/demo/ssr/point-cloud/public/video.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>WebRTC NVENC Demo</title> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="theme-color" content="#2e2e2e" /> </head> <body style="background:#2e2e2e; margin:0;"> <video autoplay muted width="800" height="600"></video> <script src="https://cdn.jsdelivr.net/npm/[email protected]/simplepeer.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.1.3/socket.io.js"></script> <script> const sock = io({ transports: ['websocket'], reconnection: true }); const video = document.querySelector('video'); const peer = new SimplePeer({ trickle: true, initiator: true, sdpTransform: (sdp) => { // Remove bandwidth restrictions // https://github.com/webrtc/samples/blob/89f17a83ed299ef28d45b933419d809b93d41759/src/content/peerconnection/bandwidth/js/main.js#L240 sdp = sdp.replace(/b=AS:.*\r\n/, '').replace(/b=TIAS:.*\r\n/, ''); // Force h264 encoding by removing all VP8/9 codecs from the sdp sdp = onlyH264(sdp); return sdp; } }); // Negotiate handshake sock.on('signal', (data) => peer.signal(data)); peer.on('signal', (data) => sock.emit('signal', data)); peer.on('data', (data) => { var decoded = new TextDecoder().decode(data); var decodedjson = JSON.parse(decoded); console.log("got data from peer: ", decodedjson.data); }); // Server video stream peer.on('stream', (stream) => { ('srcObject' in video) ? (video.srcObject = stream) : (video.src = window.URL.createObjectURL(stream)); // for older browsers video.play(); }); dispatchRemoteEvent(video, 'blur'); dispatchRemoteEvent(video, 'focus'); dispatchRemoteEvent(video, 'wheel'); dispatchRemoteEvent(window, 'beforeunload'); dispatchRemoteEvent(document, 'keyup'); dispatchRemoteEvent(document, 'keydown'); dispatchRemoteEvent(document, 'keypress'); dispatchRemoteEvent(video, 'mouseup'); dispatchRemoteEvent(video, 'mousemove'); dispatchRemoteEvent(video, 'mousedown'); dispatchRemoteEvent(video, 'mouseenter'); dispatchRemoteEvent(video, 'mouseleave'); function dispatchRemoteEvent(target, type) { let timeout = null; target.addEventListener(type, (e) => { if (target === video) { e.preventDefault(); } if (!timeout) { timeout = setTimeout(() => { timeout = null; }, 1000 / 60); peer.send(JSON.stringify({ type: 'event', data: serializeEvent(e) })); } }); } function serializeEvent(original) { return Object .getOwnPropertyNames(Object.getPrototypeOf(original)) .reduce((serialized, field) => { switch (typeof original[field]) { case 'object': case 'symbol': case 'function': break; default: serialized[field] = original[field]; } return serialized; }, { type: original.type }); } function onlyH264(sdp) { // remove non-h264 codecs from the supported codecs list const videos = sdp.match(/^m=video.*$/gm); if (videos) { return videos.map((video) => [video, [ ...getCodecIds(sdp, 'VP9'), ...getCodecIds(sdp, 'VP8'), ...getCodecIds(sdp, 'HEVC'), ...getCodecIds(sdp, 'H265') ]]).reduce((sdp, [video, ids]) => ids.reduce((sdp, id) => [ new RegExp(`^a=fmtp:${id}(.*?)$`, 'gm'), new RegExp(`^a=rtpmap:${id}(.*?)$`, 'gm'), new RegExp(`^a=rtcp-fb:${id}(.*?)$`, 'gm'), ].reduce((sdp, expr) => sdp.replace(expr, ''), sdp), sdp) .replace(video, ids.reduce((video, id) => video.replace(` ${id}`, ''), video)), sdp) .replace('\r\n', '\n').split('\n').map((x) => x.trim()).filter(Boolean).join('\r\n') + '\r\n'; } return sdp; function getCodecIds(sdp, codec) { return getIdsForMatcher(sdp, new RegExp( `^a=rtpmap:(?<id>\\d+)\\s+${codec}\\/\\d+$`, 'm' )).reduce((ids, id) => [ ...ids, id, ...getIdsForMatcher(sdp, new RegExp( `^a=fmtp:(?<id>\\d+)\\s+apt=${id}$`, 'm' )) ], []); } function getIdsForMatcher(sdp, matcher) { const ids = []; /** @type RegExpMatchArray */ let res, str = '' + sdp, pos = 0; for (; res = str.match(matcher); str = str.slice(pos)) { pos = res.index + res[0].length; if (res.groups) { ids.push(res.groups.id); } } return ids; } } </script> </body> </html>
0
rapidsai_public_repos/node/modules/demo/ssr
rapidsai_public_repos/node/modules/demo/ssr/luma/package.json
{ "private": true, "name": "@rapidsai/demo-luma.gl-lessons-ssr", "main": "index.js", "version": "22.12.2", "license": "Apache-2.0", "author": "NVIDIA, Inc. (https://nvidia.com/)", "maintainers": [ "Paul Taylor <[email protected]>" ], "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/cuda": "~22.12.2", "@rapidsai/deck.gl": "~22.12.2", "@rapidsai/demo-luma.gl-lessons": "~22.12.2", "@rapidsai/jsdom": "~22.12.2", "fastify": "3.20.2", "fastify-socket.io": "2.0.0", "fastify-static": "4.4.1", "nanoid": "3.1.31", "rxjs": "6.6.7", "shm-typed-array": "0.0.16", "simple-peer": "9.11.0", "socket.io": "4.1.3" }, "files": [ "render", "public", "copy.js", "index.js", "package.json" ] }
0