Compare commits

..
44 Commits
Author SHA1 Message Date
Matt Walsh 4a1f29cfae change to piscina 2022-07-13 23:21:58 -05:00
Matt Walsh 8b244a41a6 testing 2022-07-13 21:42:07 -05:00
Matt Walsh 97b07611e8 initial threading tests 2022-07-13 16:36:43 -05:00
Matt Walsh d108e96cea 2.6.2 2022-07-13 15:52:52 -05:00
Matt Walsh ba885085d2 minor performance optimization 2022-07-13 15:52:44 -05:00
Matt Walsh 2b6e0ba3fd 2.6.1 2022-07-13 12:01:03 -05:00
Matt Walsh 347c530edd improve hex lookup during paletizing 2022-07-13 12:00:55 -05:00
Matt Walsh a6f27875e9 2.6.0 2022-07-13 10:34:43 -05:00
Matt Walsh 1ef5053ca0 add canvas options 2022-07-13 10:34:29 -05:00
Matt Walsh ea4cb9de74 update documentation close #3 2022-07-10 21:11:07 -05:00
Matt Walsh e3c882a57c 2.5.1 2022-06-21 11:17:10 -05:00
Matt Walsh aa4b02236a remove debug logging 2022-06-21 11:17:05 -05:00
Matt Walsh 847d4cbecc 2.5.0 2022-06-21 11:13:18 -05:00
Matt Walsh 7731d64af6 fix interpertation of 300km flag 2022-06-21 11:13:11 -05:00
Matt Walsh 96d3f36545 2.4.0 2022-06-01 13:01:32 -05:00
Matt Walsh 6a7f0868a5 handle gate sizing properly for tdwr 2022-06-01 13:01:16 -05:00
Matt Walsh bed3043ccd 2.3.0 2022-05-25 23:52:30 -05:00
Matt Walsh 676c63dc1c handle super-res long range scaling properly 2022-05-25 23:51:53 -05:00
Matt Walsh e559ba1d9c better benchmark statistics 2022-05-13 10:28:26 -05:00
Matt Walsh febb902f15 2.2.1 2022-05-12 22:02:18 -05:00
Matt Walsh aa307c44c0 update nexrad-level-2-data version 2022-05-12 22:01:57 -05:00
Matt Walsh a9fd62a513 update dependencies 2022-05-12 16:02:22 -05:00
Matt Walsh c12f6bbb95 update dependencies 2022-03-30 16:16:09 -05:00
Matt Walsh 28cfd34bcd 2.2.0 2022-03-18 15:57:32 -05:00
Matt Walsh a3987914bc update nexrad-level-2-data dependency 2022-03-18 15:56:38 -05:00
Matt Walsh 2b8fbbc3b5 2.1.1 2022-03-11 13:31:01 -06:00
Matt Walsh cab1556cc4 disable preferred products for chunk mode 2022-03-11 13:30:51 -06:00
Matt Walsh 2017a6f4ff fix benchmark code 2022-03-11 09:53:14 -06:00
Matt Walsh b8389de11f 2.1.0 2022-03-11 09:13:12 -06:00
Matt Walsh dc02fe5f50 add preferred waveforms 2022-03-11 09:13:05 -06:00
Matt Walsh e9fde8161f 2.0.0 2022-03-10 23:56:32 -06:00
Matt Walsh 90025427c6 plot all elevations 2022-03-10 23:56:24 -06:00
Matt Walsh 8cea4fb15d 1.1.2 2022-01-30 16:55:57 -06:00
Matt Walsh 9b4295e872 correct nexrad-level-2-data dependency 2022-01-30 16:55:48 -06:00
Matt Walsh 483f73547b 1.1.1 2022-01-26 16:23:47 -06:00
Matt Walsh 68ab79161b remove internal console.log 2022-01-26 16:23:39 -06:00
Matt Walsh 0a781e961b 1.1.0 2021-11-04 16:05:41 -05:00
Matt Walsh 95434ea5c4 Merge branch 'indexed-colors' 2021-11-04 16:05:29 -05:00
Matt Walsh 428978c55a update readme 2021-11-04 16:04:16 -05:00
Matt Walsh 3a6fbeee3b add benchmarking 2021-11-04 14:23:30 -05:00
Matt Walsh 010642db5e rrle completed 2021-11-04 14:14:43 -05:00
Matt Walsh c9092cd8dd correct scaling 2021-11-04 12:06:33 -05:00
Matt Walsh 637064b19d restore output gitignore 2021-11-04 11:18:30 -05:00
Matt Walsh a4724e641e extract pre processing 2021-11-04 11:16:48 -05:00
22 changed files with 4551 additions and 5356 deletions

No files matched your search

+1
View File
@@ -1 +1,2 @@
node_modules node_modules
*.cpuprofile
+9
View File
@@ -0,0 +1,9 @@
{
"words": [
"nexrad",
"KSRX",
"TORD",
"palettizing",
"tdwr"
]
}
+11 -1
View File
@@ -11,7 +11,17 @@
"skipFiles": [ "skipFiles": [
"<node_internals>/**" "<node_internals>/**"
], ],
"program": "${workspaceFolder}/demos/test.js" "program": "${workspaceFolder}/demos/test.js",
"outputCapture": "std",
},
{
"type": "pwa-node",
"request": "launch",
"name": "Benchmark",
"skipFiles": [
"<node_internals>/**"
],
"program": "${workspaceFolder}/demos/benchmark.js"
} }
] ]
} }
+4 -2
View File
@@ -7,11 +7,13 @@
"KLOT", "KLOT",
"Mult", "Mult",
"NOAA", "NOAA",
"Palettized",
"RGBA",
"palettization", "palettization",
"palettize", "palettize",
"Palettized",
"palletizing", "palletizing",
"Rbga",
"RGBA",
"rrle",
"uncommenting" "uncommenting"
] ]
} }
+38 -13
View File
@@ -16,10 +16,10 @@ const { plot, writeToPngFile } = require('nexrad-level-3-plot');
// read a file // read a file
const file = fs.readFileSync('<path to data>'); const file = fs.readFileSync('<path to data>');
// parse and plot // parse and plot
const level2Plot = plot(file, {elevation: 1, product: 'REF'}); const level2Plot = plot(file, 'REF', {elevations: 1});
// use bundled utility to write to disk // use bundled utility to write to disk
(async () => { (async () => {
await writePngToFile('<path to output>.png', level2Plot.REF.canvas); await writePngToFile('<path to output>.png', level2Plot[0].REF);
})(); })();
``` ```
# Data # Data
@@ -47,15 +47,19 @@ Test code and data is provided in the `./demo` folder. `test.js` can be used to
# API # API
## plot(data, products, options) ## plot(data, products, options)
Returns an object Returns an array of objects. The order of elevations in the returned array matches the order of elevations in options.elevations
``` javascript ``` javascript
{ [
REF: { {
canvas: <Canvas>, elevation: <integer>,
palette: <Uint8ClampedArray> REF: {
canvas: <Canvas>,
palette: <Uint8ClampedArray>
},
// ... additional products
}, },
//... additional products // ... additional elevations
} ]
``` ```
The first level key in the returned object represents each requested product. The first level key in the returned object represents each requested product.
> Note: Each product may return false if no data was found for the specified elevation and product. > Note: Each product may return false if no data was found for the specified elevation and product.
@@ -73,15 +77,18 @@ options.cropTo|integer|3600|1 to 3600. After scaling and downsampling as describ
options.background|string|#000000|Background color of the image. This can be transparent by using #RGBA notation. See [ctx.fillStyle](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle) for more information. options.background|string|#000000|Background color of the image. This can be transparent by using #RGBA notation. See [ctx.fillStyle](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle) for more information.
options.lineWidth|integer|2|The raster image is created by drawing several arcs at the locations and colors specified in the data file. When scaling down you may get a better looking image by adjusting this value to something large than the default. options.lineWidth|integer|2|The raster image is created by drawing several arcs at the locations and colors specified in the data file. When scaling down you may get a better looking image by adjusting this value to something large than the default.
options.palettize|boolean\|object|false|After drawing the image convert the image from RGBA to a palettized image. When true the same palette as the product is used. Additional options are described in [palettizing](#palettizing). This can significantly reduce the size of the resulting image with minimal loss of clarity. options.palettize|boolean\|object|false|After drawing the image convert the image from RGBA to a palettized image. When true the same palette as the product is used. Additional options are described in [palettizing](#palettizing). This can significantly reduce the size of the resulting image with minimal loss of clarity.
options.elevations|undefined\|integer\|Array of integers|undefined|The specific elevations to plot. If undefined (default) all available elevations will be plotted. If an integer is provided a single elevation will be plotted with all the selected ```products```. If an array of integers are provided each ```products``` in each elevation will be plotted. Note that when a product and elevation combination do not exist the returned object will have false in the missing location. This is common where elevation 1 will have reflectivity data and elevation 2 (altough at the same angle as elevation 1) will contain velocity data.
options.usePreferredWaveforms|boolean|true|Waveform types of 1, 2, 3, 4 and 5 are produced by the radar. Type 1 is typically exclusive to reflectivity, Type 2 is typically exclusive to velocity however it also produces reflectivity data. Types 3, 4 and 5 all produce both velocity and reflectivity. When set to true type 1 waveforms will not plot velocity data, and type 2 waveforms will not plot reflectivity data. If you must see all information set this to false.
options.alpha|boolean|true|Draw on a 32-bit canvas. Passed directly to getContext('2d', {alpha}).
options.imageSmoothingEnabled|boolean|true|Enable image smoothing. Passed directly to ctx.imageSmoothingEnabled.
options.antialias|string|'default'|Enable antialias. Passed directly to ctx.antialias (part of node-canvas)
### Downsampling ### Downsampling
A full size plot is 3600 x 3600 pixels. This corresponds to the maximum range of the radar 460km (~250 mi) * maximum resolution 0.25 mi/bin * 2 (east and west side of radar). A full size plot is 3600 x 3600 pixels. This corresponds to the maximum range of the radar 460km (~250 mi) * maximum resolution 0.25 mi/bin * 2 (east and west side of radar).
options.size < 3600 will internally scale the image to the selected size. The scaling algorithm is specific to radar data and returns the maximum value over the range of bins that are combined due to the scaling factor. This ensures that maximum reflectivity or maximum velocity are preserved during the scaling process. Using an image scaling package is not preferred in this case as the scaling algorithm used my mask important data. options.size < 3600 will internally scale the image to the selected size. The scaling algorithm is specific to radar data and returns the maximum value over the range of bins that are combined due to the scaling factor. This ensures that maximum reflectivity or maximum velocity are preserved during the scaling process. Using an image scaling package is not preferred in this case as the scaling algorithm used my mask important data.
options.size > 3600 is invalid as this would cause data to be interpolated and would not be a true representation of the data returned by the radar. If you need this functionality it's recommended to use an image scaling package such as [jimp](https://www.npmjs.com/package/jimp) or [gm](https://www.npmjs.com/package/gm) on the Canvas returned by plot(). options.size > 3600 is invalid as this would cause data to be interpolated and would not be a true representation of the data returned by the radar. If you need this functionality it's recommended to use an image scaling package such as [jimp](https://www.npmjs.com/package/jimp) or [gm](https://www.npmjs.com/package/gm) on the Canvas returned by plot() which will also be much faster than the drawing methods used for a radar plot.
options.crop
### Palettizing ### Palettizing
>If used with [plotAndData()](#plotanddatafile-options) both the original image and the palettized image will be returned if used with [plot()](#plotfile-options) only the palettized image will be returned. >If used with [plotAndData()](#plotanddatafile-options) both the original image and the palettized image will be returned if used with [plot()](#plotfile-options) only the palettized image will be returned.
@@ -90,7 +97,7 @@ Plotting what is essentially polar data (raw radar data) to a cartesean coordina
This process makes use of the RGBA color space with either 3 or 4 bytes per pixel. From the standpoint of representing radar data in an image this is very inefficient use of space as typically 16 or 32 colors (> 1 byte) is necessary to show the data in it's original format. This RGBA image also does not lend itself well to PNG compression which is lossless. This process makes use of the RGBA color space with either 3 or 4 bytes per pixel. From the standpoint of representing radar data in an image this is very inefficient use of space as typically 16 or 32 colors (> 1 byte) is necessary to show the data in it's original format. This RGBA image also does not lend itself well to PNG compression which is lossless.
Palettizing introduces a compromise between image size and compresability. After the initial image is drawing the palettizing algorithm can then re-process the RGBA image and force all pixels to be one of the original color values specificed in the product's palette (options.palettize = true, the default). It can also generate an optimized palette that uses a set number of steps between the colors in the palette and the background color with a maximum generated palette size of 256 colors (options.palettize.generate = <steps>). Finally a custom palette can be provided in the form of [r1,g1,b1,r2,g2,b2,...] alpha values will be generated automatically. Palettizing introduces a compromise between image size and compresability. After the initial image is drawn the palettizing algorithm can then re-process the RGBA image and force all pixels to be one of the original color values specificed in the product's palette (options.palettize = true, the default). It can also generate an optimized palette that uses a set number of steps between the colors in the palette and the background color with a maximum generated palette size of 256 colors (options.palettize.generate = <steps>). Finally a custom palette can be provided in the form of [r1,g1,b1,r2,g2,b2,...] alpha values will be generated automatically.
A look-up table is created and cached as part of the palettization process speeding up additional calls the the palettizing function. The cache is specific to the product and options provided. A look-up table is created and cached as part of the palettization process speeding up additional calls the the palettizing function. The cache is specific to the product and options provided.
@@ -108,6 +115,24 @@ Writes a PNG file to disk. Provided as a convenience function for production and
fileName|string|A file name or path used by [fs.createWriteStream()](https://nodejs.org/api/fs.html#fs_fs_createwritestream_path_options). fileName|string|A file name or path used by [fs.createWriteStream()](https://nodejs.org/api/fs.html#fs_fs_createwritestream_path_options).
data|{canvas[palette]}|Typically the output of [plot()](#plotfile-options).\<product type>. data|{canvas[palette]}|Typically the output of [plot()](#plotfile-options).\<product type>.
# Notable and breaking changes
## v2.6.0 Notable, Additional canvas configuration options
The options antialias, imageSmoothingEnabled, and alpha were added and passed directly to the canvas context when creating it before plotting. Disabling these options (which were previously defaulted to on) can speed up plotting by about 5% and reduce output image size by up to 10% at a very slight cost of visual appearance.
## v2.5.0 Notable, 300km range now interperted correctly
Prior to this version, if the data had the ```super_res_control.300km``` flag set the resulting image would effectively be "zoomed in by 2x". Upon examing the results of this flag on the plot, reference plots and the ```gate_count``` values it was determined no scaling needed to be performed if this flag was present. Instead, the ```gate_count``` already reflects the additional data the flag indicates. This mainly affects VEL plots and some REF plots at higher elevations, depending on the VCP the radar is using.
## v2.0.0 Breaking, returns an array of objects
Previously, a single elevation would be plotted by the routine. The elevation was selected by ```options.elevation```. ```options.elevation``` has been renamed to ```options.elevations``` and will still take a single integer as an input, but in this configuration an array is still returned. The simplest way to return to the functionality of v1.1.0 is ```plot(data,products,{elevation: <integer>})[0]``` which will return only the first object in the array.
```options.elevations``` defaults to all the elevations in the provided file. This may not be the desired behavior, and will take significantly longer to plot if you do not need all of the data provided. You can query ```data.listElevations()``` to return an array of available elevations. The result can be passed directly to options.elevations or further processed to only select interesting elevations before calling ```plot()```. Additional details of ```options.elevations``` are provided above.
## v1.1.0 Notable, RRLE pre-processing
Testing and monitoring of this package in production showed that drawing each 0.5&deg; or 1.0&deg; arc as part of the plotting process was very time-expensive. Drawing a wider arc when adjacent radials had the same color at this position was significantly faster than drawing the two separate arcs.
Implementing this solution which I am calling Radial Run Length Encoding, as it spans several radials, required significant reworking of the plotting engine and resulted in much more modular code. Four pre-process routines are now run on the radar data before plotting. The first three: Downsample, FilterProduct and IndexProduct were all part of the previous version but have been extracted from the main algorithm and placed into their own modules. After each of these three modules were implemented tests were run to show that the image generated was identical to v1.0.0. The addition of the rrle pre-processing module does change the output image slightly, but these visual changes are in the level of the artifacts that are inevitable due to the polar-to-raster conversion detailed in [Palletizing](#palettizing).
# Acknowledgements # Acknowledgements
The code for this project is based upon: The code for this project is based upon:
- [Unidata](https://github.com/Unidata/thredds/blob/master/cdm/src/main/java/ucar/nc2/iosp/nexrad2/) - [Unidata](https://github.com/Unidata/thredds/blob/master/cdm/src/main/java/ucar/nc2/iosp/nexrad2/)
+52
View File
@@ -0,0 +1,52 @@
/* eslint-disable no-await-in-loop */
const { Level2Radar } = require('nexrad-level-2-data');
// eslint-disable-next-line import/no-extraneous-dependencies
const glob = require('glob');
const fs = require('fs');
const { plot, writePngToFile } = require('../src');
// list files
const files = glob.sync('./data/KLOT/KLOT20210812_171451_V*'); // ref palette tuning
// const store each file's data
const chunks = [];
// parse each file
files.forEach((file) => {
const fileBuffer = fs.readFileSync(file);
chunks.push(new Level2Radar(fileBuffer));
});
// combine data
const radarData = Level2Radar.combineData(chunks);
const size = 1800;
const iterations = 5;
// plot for each elevation and size
(async () => {
const start = new Date();
for (let i = 0; i < iterations; i += 1) {
const plots = plot(radarData, ['REF', 'VEL'], {
size,
palettize: true,
cropTo: size / 2,
alpha: false,
imageSmoothingEnabled: false,
antialias: 'none',
});
// write files to disk
const writePromises = [];
(await plots).forEach((p) => {
const { elevation } = p;
writePromises.push(writePngToFile(`./output/REF-${elevation}-${size}.png`, p.REF));
writePromises.push(writePngToFile(`./output/VEL-${elevation}-${size}.png`, p.VEL));
});
await Promise.allSettled(writePromises);
const end = new Date();
console.log(`Iteration: ${i + 1}/${iterations} Average time: ${(end - start) / 1000 / (i + 1)} s`);
}
})();
+19 -20
View File
@@ -3,16 +3,16 @@ const { Level2Radar } = require('nexrad-level-2-data');
const glob = require('glob'); const glob = require('glob');
const fs = require('fs'); const fs = require('fs');
const { plot, writeSvgToFile } = require('../src'); const { plot, writePngToFile } = require('../src');
// list files // list files
// const files = glob.sync('./data/KLOT/34/*'); // const files = glob.sync('./data/KLOT/34/*');
const files = glob.sync('./data/KLOT/381/*'); // const files = glob.sync('./data/KLOT/381/*');
// const files = glob.sync('./data/KLOT/548/*'); // const files = glob.sync('./data/KLOT/548/*');
// const files = glob.sync('./data/KLOT/940/*'); // const files = glob.sync('./data/KLOT/940/*');
// const files = glob.sync('./data/KSRX/804/*'); // const files = glob.sync('./data/KSRX/804/*');
// const files = glob.sync('./data/TORD/767/*'); // const files = glob.sync('./data/TORD/767/*');
// const files = glob.sync('./data/KLOT/KLOT20210812_171451_V*'); // ref palette tuning const files = glob.sync('./data/KLOT/KLOT20210812_171451_V*'); // ref palette tuning
// const files = glob.sync('./data/KLOT/KLOT20210621_041151_V06'); // vel palette tuning // const files = glob.sync('./data/KLOT/KLOT20210621_041151_V06'); // vel palette tuning
// const store each file's data // const store each file's data
@@ -27,13 +27,10 @@ files.forEach((file) => {
// combine data // combine data
const radarData = Level2Radar.combineData(chunks); const radarData = Level2Radar.combineData(chunks);
// result array by elevations
const plots = [];
// default to all plots unless single is specificed // default to all plots unless single is specificed
const single = process.argv.includes('single'); const single = process.argv.includes('single');
let sizes = [900, 450, 100]; let sizes = [1800];
let elevations = radarData.listElevations(); let elevations = radarData.listElevations();
if (single) { if (single) {
sizes = sizes.slice(0, 1); sizes = sizes.slice(0, 1);
@@ -46,19 +43,21 @@ if (single) {
// plot for each elevation and size // plot for each elevation and size
(async () => { (async () => {
await Promise.allSettled(sizes.map(async (size) => { await Promise.allSettled(sizes.map(async (size) => {
await Promise.allSettled(elevations.map(async (elevation) => { const plots = await plot(radarData, ['REF', 'VEL'], {
plots[elevation] = plot(radarData, ['REF', 'VEL'], { elevations,
elevation, size,
size, palettize: true,
palettize: true, elevations: 1,
// cropTo: size / 2, cropTo: size / 2,
}); });
// write files to disk // write files to disk
await Promise.allSettled([ const writePromises = [];
writeSvgToFile(`./output/REF-${elevation}-${size}.svg`, plots[elevation].REF), plots.forEach((p) => {
writeSvgToFile(`./output/VEL-${elevation}-${size}.svg`, plots[elevation].VEL), const { elevation } = p;
]); writePromises.push(writePngToFile(`./output/REF-${elevation}-${size}.png`, p.REF));
})); writePromises.push(writePngToFile(`./output/VEL-${elevation}-${size}.png`, p.VEL));
});
await Promise.allSettled(writePromises);
})); }));
})(); })();
+8
View File
@@ -0,0 +1,8 @@
{
"folders": [
{
"path": "."
}
],
"settings": {}
}
+3 -3
View File
@@ -1,4 +1,4 @@
# Ignore everything in this directory as it is generated dynamically # Ignore everything in this directory as it is generated dynamically
* *
# Except this file # Except this file
!.gitignore !.gitignore
+4049 -5139
View File
File diff suppressed because it is too large. Load diff
+38 -38
View File
@@ -1,40 +1,40 @@
{ {
"name": "nexrad-level-2-plot", "name": "nexrad-level-2-plot",
"version": "1.0.0", "version": "2.6.2",
"description": "Plotting library for nexrad-level-2-data", "description": "Plotting library for nexrad-level-2-data",
"main": "src/index.js", "main": "src/index.js",
"scripts": { "scripts": {
"test": "echo \"Error: no test specified\" && exit 1" "test": "echo \"Error: no test specified\" && exit 1"
}, },
"repository": { "repository": {
"type": "git", "type": "git",
"url": "git+https://github.com/netbymatt/nexrad-level-2-plot.git" "url": "git+https://github.com/netbymatt/nexrad-level-2-plot.git"
}, },
"keywords": [ "keywords": [
"NEXRAD", "NEXRAD",
"level", "level",
"2", "2",
"radar", "radar",
"plot" "plot"
], ],
"author": "Matt Walsh", "author": "Matt Walsh",
"license": "MIT", "license": "MIT",
"bugs": { "bugs": {
"url": "https://github.com/netbymatt/nexrad-level-2-plot/issues" "url": "https://github.com/netbymatt/nexrad-level-2-plot/issues"
}, },
"homepage": "https://github.com/netbymatt/nexrad-level-2-plot#readme", "homepage": "https://github.com/netbymatt/nexrad-level-2-plot#readme",
"dependencies": { "dependencies": {
"@svgdotjs/svg.js": "^3.1.1", "canvas": "^2.9.3",
"nexrad-level-2-data": "file:../nexrad-level-2-data", "nexrad-level-2-data": "../nexrad-level-2-data",
"svgdom": "^0.1.8" "piscina": "^3.2.0"
}, },
"devDependencies": { "devDependencies": {
"eslint": "^7.32.0", "eslint": "^8.0.0",
"eslint-config-airbnb-base": "^14.2.1", "eslint-config-airbnb-base": "^15.0.0",
"eslint-plugin-import": "^2.23.4", "eslint-plugin-import": "^2.23.4",
"glob": "^7.1.7" "glob": "^7.1.7"
}, },
"engines": { "engines": {
"node": ">=13.0.0" "node": ">=13.0.0"
} }
} }
+89 -104
View File
@@ -1,8 +1,15 @@
const { createSVGWindow } = require('svgdom'); const canvasObj = require('canvas');
const { SVG, registerWindow } = require('@svgdotjs/svg.js'); const { createCanvas } = canvasObj;
const Palette = require('./palettes'); const Palette = require('./palettes');
const palettizeImage = require('./palettize');
// data pre-processing
const filterProduct = require('./preprocess/filterproduct');
const downSample = require('./preprocess/downsample');
const indexProduct = require('./preprocess/indexproduct');
const rrle = require('./preprocess/rrle');
// names of data structures keyed to product name // names of data structures keyed to product name
const dataNames = { const dataNames = {
@@ -28,6 +35,14 @@ const palettes = {
}; };
/* eslint-enable global-require */ /* eslint-enable global-require */
const preferredWaveformUsage = {
1: ['REF', 'SW ', 'ZDR', 'PHI', 'RHO'],
2: ['VEL'],
3: ['REF', 'VEL', 'SW ', 'ZDR', 'PHI', 'RHO'],
4: ['REF', 'VEL', 'SW ', 'ZDR', 'PHI', 'RHO'],
5: ['REF', 'VEL', 'SW ', 'ZDR', 'PHI', 'RHO'],
};
// default options // default options
const DEFAULT_OPTIONS = { const DEFAULT_OPTIONS = {
// must be a square image // must be a square image
@@ -35,50 +50,57 @@ const DEFAULT_OPTIONS = {
cropTo: 3600, cropTo: 3600,
background: 'black', background: 'black',
lineWidth: 2, lineWidth: 2,
}; usePreferredWaveforms: true,
alpha: true,
// calculation constants imageSmoothingEnabled: true,
const RAD45 = (45 * Math.PI / 180); antialias: 'default',
const RAD90 = RAD45 * 2;
// round to specified number of decimal points
const roundTo = (decimals, value) => Math.round(value * 10 ** decimals) / 10 ** decimals;
// polar to cartesean conversion
const polarToCartesean = (r, theta) => {
const x = roundTo(2, r * Math.cos(theta));
const y = roundTo(2, r * Math.sin(theta));
return {
x, y,
};
}; };
const draw = (data, _options) => { const draw = (data, _options) => {
// create a new window
const window = createSVGWindow();
const { document } = window;
// register window and document
registerWindow(window, document);
// combine options with defaults // combine options with defaults
const options = { const options = {
...DEFAULT_OPTIONS, ...DEFAULT_OPTIONS,
..._options, ..._options,
}; };
// check preferred waveforms
const elevationInfo = data?.vcp?.record?.elevations?.[options?.elevation];
// elevation info is not available in chunks mode, so preferred waveforms cannot be processed
if (elevationInfo) {
const preferredProducts = preferredWaveformUsage[elevationInfo.waveform_type];
if (options.usePreferredWaveforms && !preferredProducts.includes(options.product)) return false;
}
// calculate scale // calculate scale
if (options.size > DEFAULT_OPTIONS.size) throw new Error(`Upsampling is not supported. Provide a size <= ${DEFAULT_OPTIONS.size}`); if (options.size > DEFAULT_OPTIONS.size) throw new Error(`Upsampling is not supported. Provide a size <= ${DEFAULT_OPTIONS.size}`);
if (options.size < 1) throw new Error('Provide options.size > 0'); if (options.size < 1) throw new Error('Provide options.size > 0');
const scale = DEFAULT_OPTIONS.size / options.size; const scale = DEFAULT_OPTIONS.size / options.size;
// wsr88d uses a gate size of 0.25km, tdwr uses a gate size of 0.15km, although it is reported as 0.3km for processing reasons
// this calculation scales the plot accordingly to the nominal 0.25km so all generated plots are at the same scale
const rawGateSize = data?.data?.[options.elevation]?.[0]?.record?.reflect?.gate_size ?? 0.25;
const realGateSize = rawGateSize !== 0.3 ? rawGateSize : rawGateSize / 2;
const gateSizeScaling = 0.25 / realGateSize;
// calculate crop, adjust if necessary // calculate crop, adjust if necessary
const cropTo = Math.min(options.size, options.cropTo); const cropTo = Math.min(options.size, options.cropTo);
if (options.cropTo < 1) throw new Error('Provide options.cropTo > 0'); if (options.cropTo < 1) throw new Error('Provide options.cropTo > 0');
// create the canvas // create the canvas and context
const canvas = SVG(document.documentElement); const canvas = createCanvas(cropTo, cropTo);
canvas.size(cropTo, cropTo); const ctx = canvas.getContext('2d', { alpha: options.alpha });
canvas.viewbox(-cropTo / 2, -cropTo / 2, cropTo, cropTo); ctx.antialias = options.antialias;
ctx.imageSmoothingEnabled = options.imageSmoothingEnabled;
// fill background with black
ctx.fillStyle = options.background;
ctx.fillRect(0, 0, cropTo, cropTo);
// canvas settings
ctx.imageSmoothingEnabled = true;
ctx.lineWidth = options.lineWidth / gateSizeScaling;
ctx.translate(cropTo / 2, cropTo / 2);
ctx.rotate(-Math.PI / 2);
// get the palette // get the palette
const palette = palettes[options.product]; const palette = palettes[options.product];
@@ -92,7 +114,7 @@ const draw = (data, _options) => {
// calculate resolution in radians, default to 1° // calculate resolution in radians, default to 1°
let resolution = Math.PI / 180; let resolution = Math.PI / 180;
if (data?.vcp?.record?.elevation?.s[options.elevation]?.super_res_control?.super_res?.halfDegreeAzimuth) resolution /= 2; if (data?.vcp?.record?.elevations?.[options.elevation]?.super_res_control?.super_res?.halfDegreeAzimuth) resolution /= 2;
// calculate half resolution step for additional calculations below // calculate half resolution step for additional calculations below
const halfResolution = resolution / 2; const halfResolution = resolution / 2;
@@ -107,96 +129,59 @@ const draw = (data, _options) => {
// check for data for this product // check for data for this product
if (headers[0][dataName] === undefined) return false; if (headers[0][dataName] === undefined) return false;
const paths = {}; // pre-processing
const filteredProduct = filterProduct(headers, dataName);
const downSampledProduct = downSample(filteredProduct, scale, resolution, options, palette);
const indexedProduct = indexProduct(downSampledProduct, palette);
const rrlEncoded = rrle(indexedProduct, resolution);
// loop through data // loop through data
headers.forEach((header) => { rrlEncoded.forEach((radial) => {
// get correct data
const thisRadial = header[dataName];
// skip if this radial isn't found
if (thisRadial === undefined) return;
// calculate plotting parameters // calculate plotting parameters
const deadZone = thisRadial.first_gate / thisRadial.gate_size; const deadZone = radial.first_gate / radial.gate_size / scale;
const startAngle = header.azimuth * (Math.PI / 180) - halfResolution; // 10% is added to the arc to ensure that each arc bleeds into the next just slightly to avoid radial empty spaces at further distances
const endAngle = startAngle + resolution; const startAngle = radial.azimuth * (Math.PI / 180) - halfResolution * 1.1;
const endAngle = radial.azimuth * (Math.PI / 180) + halfResolution * 1.1;
// track max value for downsampling(d)
let downsampled = 0;
let lastRemainder = 0;
// calculate maximum bin to plot based on azimuth
// wrap azimuth to 90° offset by -45° (% in js is remainder, the formula below make it in to modulus)
const azWrap = (((startAngle - RAD45) % RAD90) + RAD90) % RAD90;
// calculate a magnitude multiplier as 1/sin with 45° shift removed
const azMagnitudeMult = 1 / Math.abs(Math.sin(azWrap + RAD45));
const cropMaxBin = Math.ceil(Math.abs(options.cropTo / 2 * scale * azMagnitudeMult));
// compare max calculated value with length of radial
const maxBin = Math.min(cropMaxBin, thisRadial.moment_data.length);
// plot each bin // plot each bin
for (let idx = 0; idx < maxBin; idx += 1) { radial.moment_data.forEach((bin, idx) => {
// get the value if (bin === null) return;
const bin = thisRadial.moment_data[idx];
// skip null values
if (bin !== null) {
let thisSample;
// test for downsampling
if (scale !== 1) {
const remainder = idx % scale;
// test for rollover in scaling
if (remainder < lastRemainder) {
// plot this point and reset values
thisSample = downsampled;
downsampled = 0;
}
// store this sample if it meets downsample requirements ctx.beginPath();
downsampled = palette.downSample(bin, downsampled); // different methods for rrle encoded or not
// store for rollover tracking if (bin.count) {
lastRemainder = remainder; // rrle encoded
} else { ctx.strokeStyle = palette.lookupRgba[bin.value];
thisSample = bin; ctx.arc(0, 0, (idx + deadZone) * gateSizeScaling, startAngle, endAngle + resolution * (bin.count - 1));
} } else {
// plain data
// see if there's a sample to plot ctx.strokeStyle = palette.lookupRgba[bin];
if (thisSample && !palette.inDeadband(thisSample)) { ctx.arc(0, 0, (idx + deadZone) * gateSizeScaling, startAngle, endAngle);
// get color
const color = palette.findColorRgba(thisSample);
if (!paths[color]) paths[color] = [];
// calculate radius
const r = (idx + deadZone) / scale;
const rRounded = roundTo(2, r);
// calculate start of arc
const arcStartCartesean = polarToCartesean(r, startAngle);
paths[color].push(['M', arcStartCartesean.x, arcStartCartesean.y]);
// calculate end of arc
const arcEndCartesean = polarToCartesean(r, endAngle);
// end of arc and flags
paths[color].push(['A', rRounded, rRounded, 0, 0, 0, arcEndCartesean.x, arcEndCartesean.y]);
}
} }
} ctx.stroke();
}); });
// draw each path
Object.entries(paths).forEach(([color, path]) => {
path.push('z');
canvas.path(path.flat()).stroke({ color });
}); });
if (!options.palettize) {
// return the palette and canvas
return {
canvas,
};
}
// palettize image
const palettized = palettizeImage(ctx, palette);
// return palettized image
return { return {
canvas, canvas: palettized,
palette: palette.getPalette(),
}; };
}; };
module.exports = { module.exports = {
draw, draw,
DEFAULT_OPTIONS, DEFAULT_OPTIONS,
canvas: canvasObj,
}; };
+1
View File
@@ -0,0 +1 @@
module.exports = ['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '0a', '0b', '0c', '0d', '0e', '0f', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '1a', '1b', '1c', '1d', '1e', '1f', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '2a', '2b', '2c', '2d', '2e', '2f', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '3a', '3b', '3c', '3d', '3e', '3f', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '4a', '4b', '4c', '4d', '4e', '4f', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '5a', '5b', '5c', '5d', '5e', '5f', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '6a', '6b', '6c', '6d', '6e', '6f', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '7a', '7b', '7c', '7d', '7e', '7f', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '8a', '8b', '8c', '8d', '8e', '8f', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '9a', '9b', '9c', '9d', '9e', '9f', 'a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'aa', 'ab', 'ac', 'ad', 'ae', 'af', 'b0', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'b9', 'ba', 'bb', 'bc', 'bd', 'be', 'bf', 'c0', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'ca', 'cb', 'cc', 'cd', 'ce', 'cf', 'd0', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8', 'd9', 'da', 'db', 'dc', 'dd', 'de', 'df', 'e0', 'e1', 'e2', 'e3', 'e4', 'e5', 'e6', 'e7', 'e8', 'e9', 'ea', 'eb', 'ec', 'ed', 'ee', 'ef', 'f0', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'fa', 'fb', 'fc', 'fd', 'fe', 'ff'];
+20 -6
View File
@@ -4,6 +4,8 @@
// this ensures that the colors are not blended because the index should be returned in the a position // this ensures that the colors are not blended because the index should be returned in the a position
// after the entire image is drawn the index information must be shifted from g to a // after the entire image is drawn the index information must be shifted from g to a
const hexLookup = require('./hexlookup');
const rgbaLookupSize = 200; const rgbaLookupSize = 200;
class Palette { class Palette {
@@ -12,6 +14,7 @@ class Palette {
this.limits = palette.limits; this.limits = palette.limits;
this.transparentIndex = palette.transparentIndex; this.transparentIndex = palette.transparentIndex;
this.lookupRgba = findDbzRbgaGenerator(this.limits, this.palette, palette.maxDbzIndex); this.lookupRgba = findDbzRbgaGenerator(this.limits, this.palette, palette.maxDbzIndex);
this.lookupIndex = findDbzIndexGenerator(this.limits, this.palette, palette.maxDbzIndex);
this.closest = {}; this.closest = {};
// these may not exist and are overridden with default functions // these may not exist and are overridden with default functions
@@ -33,9 +36,9 @@ class Palette {
} }
} }
findColorRgba(dbz) { findColorIndex(dbz) {
// find the rgba value of the color from the provided dbz value // find the rgba value of the color from the provided dbz value
return this.lookupRgba[Math.trunc(dbz + rgbaLookupSize)]; return this.lookupIndex[Math.trunc(dbz + rgbaLookupSize)];
} }
getPalette() { getPalette() {
@@ -58,7 +61,8 @@ class Palette {
// short circuit for transparent (black) // short circuit for transparent (black)
if (match[0] <= 2 && match[1] <= 2 && match[2] <= 2) return this.transparentIndex; if (match[0] <= 2 && match[1] <= 2 && match[2] <= 2) return this.transparentIndex;
// short circuit previously calculated matches // short circuit previously calculated matches
const asHex = match[0].toString(16).padStart(2, '0') + match[1].toString(16).padStart(2, '0') + match[2].toString(16).padStart(2, '0'); const asHex = hexLookup[match[0]] + hexLookup[match[1]] + hexLookup[match[2]];
// const asHex = match[0].toString(16).padStart(2, '0') + match[1].toString(16).padStart(2, '0') + match[2].toString(16).padStart(2, '0');
if (this.closest[asHex]) return this.closest[asHex]; if (this.closest[asHex]) return this.closest[asHex];
// initial conditions // initial conditions
let closestIndex = 0; let closestIndex = 0;
@@ -79,19 +83,29 @@ class Palette {
} }
// geometric distance // geometric distance
// square root is intentionally not taken for performance reasons
static geometricDistance(a, b) { static geometricDistance(a, b) {
return a.reduce((acc, val, idx) => acc + (val - b[idx]) ** 2, 0); return a.reduce((acc, val, idx) => acc + (val - b[idx]) ** 2, 0);
} }
} }
// create a lookup table of colors for faster processing // create a lookup table for indices generated by findDbzIndexGenerator
const findDbzRbgaGenerator = (limits, palette, maxDbzIndex = 14) => { const findDbzRbgaGenerator = (limits, palette) => {
const lookupRgba = [];
for (let i = 0; i < palette.length; i += 4) {
lookupRgba.push(`rgba(${palette[i]},${palette[i + 1]},${palette[i + 2]},${palette[(i + 3)] / 255})`);
}
return lookupRgba;
};
// create a lookup table of colors by palette index
const findDbzIndexGenerator = (limits, palette, maxDbzIndex = 14) => {
const lookupRgba = []; const lookupRgba = [];
for (let i = -rgbaLookupSize; i <= rgbaLookupSize; i += 1) { for (let i = -rgbaLookupSize; i <= rgbaLookupSize; i += 1) {
let index = limits.findIndex((limit) => i < limit); let index = limits.findIndex((limit) => i < limit);
// a value of -1 means it is off the end of the scale, set to highest value // a value of -1 means it is off the end of the scale, set to highest value
if (index === -1) index = maxDbzIndex; if (index === -1) index = maxDbzIndex;
lookupRgba.push(`rgba(${palette[index * 4]},${palette[index * 4 + 1]},${palette[index * 4 + 2]},${palette[(index * 4 + 3)] / 255})`); lookupRgba.push(index);
} }
return lookupRgba; return lookupRgba;
}; };
+1 -3
View File
@@ -6,7 +6,6 @@ const palettizeImage = (sourceCtx, palette) => {
x: sourceCtx.canvas.width, x: sourceCtx.canvas.width,
y: sourceCtx.canvas.height, y: sourceCtx.canvas.height,
}; };
console.time('Palettize image');
// transform into indexed palette by finding the closest indexed color for each pixel // transform into indexed palette by finding the closest indexed color for each pixel
// create a destination image that is transparent and indexed // create a destination image that is transparent and indexed
@@ -19,11 +18,10 @@ const palettizeImage = (sourceCtx, palette) => {
const indexedImageData = indexedCtx.getImageData(0, 0, dim.x, dim.y); const indexedImageData = indexedCtx.getImageData(0, 0, dim.x, dim.y);
// loop through each pixel // loop through each pixel
console.log(`Palettized cache size: ${Object.keys(palette.closest).length}`);
indexedImageData.data.forEach((val, idx) => { indexedImageData.data.forEach((val, idx) => {
indexedImageData.data[idx] = palette.closestIndex(sourceImageData.data.slice(idx * 4, idx * 4 + 3)); indexedImageData.data[idx] = palette.closestIndex(sourceImageData.data.slice(idx * 4, idx * 4 + 3));
}); });
console.timeEnd('Palettize image');
// write the new image data // write the new image data
indexedCtx.putImageData(indexedImageData, 0, 0); indexedCtx.putImageData(indexedImageData, 0, 0);
+56
View File
@@ -0,0 +1,56 @@
// downsample the moment data preserving the maximum dbz using palette.downSample
// this includes "cropping" the data to the specified size
// calculation constants
const RAD45 = (45 * Math.PI / 180);
const RAD90 = RAD45 * 2;
const downSample = (radials, scale, resolution, options, palette) => {
// no scaling, just pass through data
if (scale === 1) return radials;
const halfResolution = resolution / 2;
// perform downsampling of each radial/moment combination
return radials.map((radial) => {
const newMomentData = [];
// track max value for downsampling(d)
let downsampled = null;
let lastRemainder = 0;
const azimuth = radial.azimuth * (Math.PI / 180) - halfResolution;
// calculate maximum bin to plot based on azimuth
// wrap azimuth to 90° offset by -45° (% in js is remainder, the formula below makes it in to modulus)
const azWrap = (((azimuth - RAD45) % RAD90) + RAD90) % RAD90;
// calculate a magnitude multiplier as 1/sin with 45° shift removed
const azMagnitudeMult = 1 / Math.abs(Math.sin(azWrap + RAD45));
const cropMaxBin = Math.ceil(Math.abs(options.cropTo / 2 * scale * azMagnitudeMult));
// compare max calculated value with length of radial
const maxBin = Math.min(cropMaxBin, radial.moment_data.length);
for (let idx = 0; idx < maxBin; idx += 1) {
// get the value
const bin = radial.moment_data[idx];
const remainder = idx % scale;
// test for rollover in scaling
if (remainder < lastRemainder) {
// plot this point and reset values
newMomentData.push(downsampled);
downsampled = null;
}
// store this sample if it meets downsample requirements
downsampled = palette.downSample(bin, downsampled);
// store for rollover tracking
lastRemainder = remainder;
}
return {
...radial,
moment_data: newMomentData,
};
});
};
module.exports = downSample;
+16
View File
@@ -0,0 +1,16 @@
// accomplish some pre-processing in one loop
// filter data for a specific product
// add the necessary azimuth data
const filterProduct = (data, product) => data.map((header) => {
// get correct data
const thisRadial = header[product];
// skip if this radial isn't found
if (thisRadial === undefined) return false;
thisRadial.azimuth = header.azimuth;
return thisRadial;
// remove any missing radials
}).filter((d) => d);
module.exports = filterProduct;
+16
View File
@@ -0,0 +1,16 @@
// take the raw data values and turn them into indexed values in the palette
// this is the first step in palettizing and in the Radial run-length encoding process
const indexProduct = (radials, palette) => radials.map((radial) => {
const indexedMoment = radial.moment_data.map((bin) => {
if (bin === null) return null;
if (palette.inDeadband(bin)) return null;
return palette.findColorIndex(bin);
});
return {
...radial,
moment_data: indexedMoment,
};
});
module.exports = indexProduct;
+76
View File
@@ -0,0 +1,76 @@
// radial run-length encoding
// encode run length data to the adjacent radials, instead of along the length of the radial
const findTotalMatches = (radials, startI, binIdx, resolutionThreshold) => {
// get the target value
const target = radials[startI].moment_data[binIdx];
// start a counter for matches
let count = 1;
// start a counter for the remaining radials
let nextI = startI + 1;
// track the current azimuth
let currentAzimuth = radials[startI].azimuth;
// loop ending variable
let checkNext = true;
// loop through all available radials and count up matches
// end condition is the number of radials available
// a radial not within the resolution threshold
// or the binIdx under test not present in one of the next radials
while (checkNext && nextI < radials.length) {
// reset flag
checkNext = false;
const nextAzimuth = radials[nextI].azimuth;
if (nextAzimuth - currentAzimuth < resolutionThreshold) {
// get the next bin
const nextBin = radials[nextI].moment_data[binIdx];
// check for match, and out of bounds condition above will return undefined which will fail the match
if (nextBin === target) {
// we matched, let the next loop iteration run
checkNext = true;
// update values for next round
currentAzimuth = nextAzimuth;
nextI += 1;
count += 1;
}
}
}
// don't return a count of 1 if no matches were found
if (count === 1) return false;
return count;
};
const rrle = (radials, resolutionRad) => {
// calculate the nominal angle to the next radial plus 20% to easily account for floating point inaccuracies
const resolutionThreshold = resolutionRad * 180 / Math.PI * 1.2;
// sort the radials by azimuth, 0 > 360
const sorted = radials.sort((a, b) => a.azimuth - b.azimuth);
// scan each radial
const maxRadial = sorted.length;
for (let i = 0; i < maxRadial; i += 1) {
// get this radial
const radial = sorted[i];
// look at each bin on the radial
radial.moment_data.forEach((bin, binIdx) => {
if (radials[i].moment_data[binIdx] === null) return;
const totalMatches = findTotalMatches(radials, i, binIdx, resolutionThreshold);
// if a total match was found update the bin data and null out the remaining bins in the run
if (!totalMatches) return;
radial.moment_data[binIdx] = { value: bin, count: totalMatches };
const loopEnd = i + totalMatches - 1;
for (let clearI = i + 1; clearI <= loopEnd; clearI += 1) {
sorted[clearI].moment_data[binIdx] = null;
}
});
}
return radials;
};
module.exports = rrle;
+9
View File
@@ -0,0 +1,9 @@
const { Level2Radar } = require('nexrad-level-2-data');
const { workerData } = require('piscina');
const { draw } = require('./index');
module.exports = (options) => {
const level2Radar = Level2Radar(workerData);
const plot = draw(level2Radar, options);
return plot;
};
+35 -15
View File
@@ -1,5 +1,8 @@
const { draw, canvas } = require('./draw'); const { Piscina } = require('piscina');
const { writePngToFile, writeSvgToFile } = require('./utils/file'); const path = require('path');
const { canvas } = require('./draw');
const { writePngToFile } = require('./utils/file');
/** /**
* Plot level 2 data * Plot level 2 data
* @param {Level2Data} data output from the nexrad-level-2-data library * @param {Level2Data} data output from the nexrad-level-2-data library
@@ -10,12 +13,14 @@ const { writePngToFile, writeSvgToFile } = require('./utils/file');
* @param {string} [options.background=#000000] Background color of the image. This can be transparent by using #RGBA notation. * @param {string} [options.background=#000000] Background color of the image. This can be transparent by using #RGBA notation.
* @param {number} [options.lineWidth=2] The raster image is created by drawing several arcs at the locations and colors specified in the data file. When scaling down you may get a better looking image by adjusting this value to something large than the default. * @param {number} [options.lineWidth=2] The raster image is created by drawing several arcs at the locations and colors specified in the data file. When scaling down you may get a better looking image by adjusting this value to something large than the default.
* @param {(boolean|object)} [options.palettize] After drawing the image convert the image from RGBA to a palettized image. When true the same palette as the product is used. * @param {(boolean|object)} [options.palettize] After drawing the image convert the image from RGBA to a palettized image. When true the same palette as the product is used.
* @param {(undefined|number|number[])} [options.elevations=undefined] List of elevations to plot.
* @param {boolean} [options.usePreferredWaveforms = true] Limit the plotted data to the preferred use of waveforms 1 and 2.
* @param {boolean} [options.alpha = true] Draw on a 32-bit canvas. Passed directly to getContext('2d', {alpha}).
* @param {boolean} [options.imageSmoothingEnabled = true] Control image smoothing. Passed directly to ctx.imageSmoothingEnabled.
* @param {string} [options.antialias = 'default'] Control antialias. Passed directly to ctx.antialias (part of node-canvas)
* @returns Canvas * @returns Canvas
*/ */
const plot = (data, _products, options) => { const plot = async (data, _products, options) => {
// store result
const result = {};
let products; let products;
// make product list into an array // make product list into an array
if (_products && Array.isArray(_products)) { if (_products && Array.isArray(_products)) {
@@ -28,22 +33,37 @@ const plot = (data, _products, options) => {
} }
// get the available elevations // get the available elevations
const elevations = data.listElevations(); const availableElevations = data.listElevations();
if (elevations.length === 0) throw new Error('No elevations availabe'); if (availableElevations.length === 0) throw new Error('No elevations availabe');
products.forEach((product) => { // handle options.elevations defaults
// parse and store result let elevations = options?.elevations;
result[product] = draw(data, { if (!elevations) elevations = availableElevations;
...options, if (typeof elevations === 'number') elevations = [elevations];
product,
}); const staticPool = new Piscina({
filename: path.resolve(__dirname, './draw/thread.js'),
workerData: data.toObject(),
}); });
const result = await Promise.all(elevations.map(async (elevation) => {
const elevationResult = { elevation };
await Promise.all(products.map(async (product) => {
// parse and store result
elevationResult[product] = await staticPool.run({
...options,
elevation,
product,
});
}));
return elevationResult;
}));
staticPool.destroy();
return result; return result;
}; };
module.exports = { module.exports = {
plot, plot,
writePngToFile, writePngToFile,
writeSvgToFile,
canvas, canvas,
}; };
-12
View File
@@ -26,18 +26,6 @@ const writePngToFile = (fileName, data) => new Promise((resolve, reject) => {
writeStream.on('error', (e) => reject(e)); writeStream.on('error', (e) => reject(e));
}); });
const writeSvgToFile = async (fileName, data) => {
// the draw function will return false if no data was found, short circuit the output here
if (!data.canvas) {
return;
}
// write to the stream
await fs.promises.writeFile(fileName, data.canvas.svg());
console.log(fileName);
};
module.exports = { module.exports = {
writePngToFile, writePngToFile,
writeSvgToFile,
}; };