mirror of
https://github.com/netbymatt/nexrad-level-2-plot.git
synced 2026-11-28 18:28:05 -08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cc1515cff3 | ||
|
|
62b92f9391 | ||
|
|
9b3e59d78a | ||
|
|
5c5726d119 | ||
|
|
769d4c26e0 | ||
|
|
894772ccbf | ||
|
|
c9b7790eca | ||
|
|
12031fb807 | ||
|
|
d13142052e | ||
|
|
ea23ea2e68 | ||
|
|
53857aabd9 | ||
|
|
7ea73c0cc6 | ||
|
|
6ca3b0816f | ||
|
|
86c2f9e8ee | ||
|
|
f881493aa4 | ||
|
|
5767f2a10e | ||
|
|
a718f5c3e3 | ||
|
|
20c4552d0a | ||
|
|
d108e96cea | ||
|
|
ba885085d2 | ||
|
|
2b6e0ba3fd | ||
|
|
347c530edd | ||
|
|
a6f27875e9 | ||
|
|
1ef5053ca0 | ||
|
|
ea4cb9de74 | ||
|
|
e3c882a57c | ||
|
|
aa4b02236a | ||
|
|
847d4cbecc | ||
|
|
7731d64af6 | ||
|
|
96d3f36545 | ||
|
|
6a7f0868a5 | ||
|
|
bed3043ccd | ||
|
|
676c63dc1c | ||
|
|
e559ba1d9c | ||
|
|
febb902f15 | ||
|
|
aa307c44c0 | ||
|
|
a9fd62a513 | ||
|
|
c12f6bbb95 |
No files matched your search
@@ -1,78 +0,0 @@
|
|||||||
module.exports = {
|
|
||||||
root: true,
|
|
||||||
env: {
|
|
||||||
browser: true,
|
|
||||||
commonjs: true,
|
|
||||||
node: true,
|
|
||||||
jquery: true,
|
|
||||||
},
|
|
||||||
extends: 'airbnb-base',
|
|
||||||
globals: {
|
|
||||||
Atomics: 'readonly',
|
|
||||||
SharedArrayBuffer: 'readonly',
|
|
||||||
},
|
|
||||||
parserOptions: {
|
|
||||||
ecmaVersion: 2020,
|
|
||||||
},
|
|
||||||
rules: {
|
|
||||||
indent: [
|
|
||||||
'error',
|
|
||||||
'tab',
|
|
||||||
],
|
|
||||||
'no-use-before-define': [
|
|
||||||
'error',
|
|
||||||
{
|
|
||||||
variables: false,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
'no-param-reassign': [
|
|
||||||
'error',
|
|
||||||
{
|
|
||||||
props: false,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
'no-tabs': 0,
|
|
||||||
'no-console': 0,
|
|
||||||
'max-len': 0,
|
|
||||||
'linebreak-style': 0,
|
|
||||||
quotes: [
|
|
||||||
'error',
|
|
||||||
'single',
|
|
||||||
],
|
|
||||||
semi: [
|
|
||||||
'error',
|
|
||||||
'always',
|
|
||||||
],
|
|
||||||
'no-prototype-builtins': 0,
|
|
||||||
'comma-dangle': ['error', 'always-multiline'],
|
|
||||||
'block-scoped-var': ['error'],
|
|
||||||
'default-case': ['error'],
|
|
||||||
'default-param-last': ['error'],
|
|
||||||
'dot-location': ['error', 'property'],
|
|
||||||
eqeqeq: ['error'],
|
|
||||||
'no-eval': ['error'],
|
|
||||||
'no-eq-null': ['error'],
|
|
||||||
'no-floating-decimal': ['error'],
|
|
||||||
'no-trailing-spaces': ['error'],
|
|
||||||
'brace-style': [2, '1tbs', { allowSingleLine: true }],
|
|
||||||
'no-mixed-operators': [
|
|
||||||
'error',
|
|
||||||
{
|
|
||||||
groups: [
|
|
||||||
['&', '|', '^', '~', '<<', '>>', '>>>'],
|
|
||||||
['==', '!=', '===', '!==', '>', '>=', '<', '<='],
|
|
||||||
['&&', '||'],
|
|
||||||
['in', 'instanceof'],
|
|
||||||
],
|
|
||||||
allowSamePrecedence: true,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
'no-underscore-dangle': ['error', {
|
|
||||||
allowAfterThis: true,
|
|
||||||
}],
|
|
||||||
'no-bitwise': 0,
|
|
||||||
},
|
|
||||||
ignorePatterns: [
|
|
||||||
'*.min.js',
|
|
||||||
],
|
|
||||||
};
|
|
||||||
@@ -1 +1,2 @@
|
|||||||
node_modules
|
node_modules
|
||||||
|
*.cpuprofile
|
||||||
Vendored
+9
@@ -0,0 +1,9 @@
|
|||||||
|
{
|
||||||
|
"words": [
|
||||||
|
"nexrad",
|
||||||
|
"KSRX",
|
||||||
|
"TORD",
|
||||||
|
"palettizing",
|
||||||
|
"tdwr"
|
||||||
|
]
|
||||||
|
}
|
||||||
Vendored
+4
-4
@@ -5,22 +5,22 @@
|
|||||||
"version": "0.2.0",
|
"version": "0.2.0",
|
||||||
"configurations": [
|
"configurations": [
|
||||||
{
|
{
|
||||||
"type": "pwa-node",
|
"type": "node",
|
||||||
"request": "launch",
|
"request": "launch",
|
||||||
"name": "Test",
|
"name": "Test",
|
||||||
"skipFiles": [
|
"skipFiles": [
|
||||||
"<node_internals>/**"
|
"<node_internals>/**"
|
||||||
],
|
],
|
||||||
"program": "${workspaceFolder}/demos/test.js"
|
"program": "${workspaceFolder}/demos/test.mjs"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"type": "pwa-node",
|
"type": "node",
|
||||||
"request": "launch",
|
"request": "launch",
|
||||||
"name": "Benchmark",
|
"name": "Benchmark",
|
||||||
"skipFiles": [
|
"skipFiles": [
|
||||||
"<node_internals>/**"
|
"<node_internals>/**"
|
||||||
],
|
],
|
||||||
"program": "${workspaceFolder}/demos/benchmark.js"
|
"program": "${workspaceFolder}/demos/benchmark.mjs"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -2,6 +2,9 @@
|
|||||||
|
|
||||||
> A javascript implementation for plotting Nexrad Level II data parsed via [nexrad-level-2-data](https://github.com/netbymatt/nexrad-level-2-data/).
|
> A javascript implementation for plotting Nexrad Level II data parsed via [nexrad-level-2-data](https://github.com/netbymatt/nexrad-level-2-data/).
|
||||||
|
|
||||||
|
# Demo
|
||||||
|
A live demo showing the output of this library (via [nexrad-level-2-data](https://www.github.com/netbymatt/nexrad-level-2-data)) for select radar sites is available at https://nexrad-demo.netbymatt.com/
|
||||||
|
|
||||||
# Use
|
# Use
|
||||||
## Install
|
## Install
|
||||||
```bash
|
```bash
|
||||||
@@ -16,10 +19,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
|
||||||
@@ -56,7 +59,7 @@ Returns an array of objects. The order of elevations in the returned array match
|
|||||||
canvas: <Canvas>,
|
canvas: <Canvas>,
|
||||||
palette: <Uint8ClampedArray>
|
palette: <Uint8ClampedArray>
|
||||||
},
|
},
|
||||||
//... additional products
|
// ... additional products
|
||||||
},
|
},
|
||||||
// ... additional elevations
|
// ... additional elevations
|
||||||
]
|
]
|
||||||
@@ -79,6 +82,9 @@ options.lineWidth|integer|2|The raster image is created by drawing several arcs
|
|||||||
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.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.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).
|
||||||
@@ -114,6 +120,12 @@ data|{canvas[palette]}|Typically the output of [plot()](#plotfile-options).\<pro
|
|||||||
|
|
||||||
# Notable and breaking changes
|
# 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
|
## 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.
|
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.
|
||||||
|
|
||||||
|
|||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,47 +0,0 @@
|
|||||||
/* 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;
|
|
||||||
|
|
||||||
// plot for each elevation and size
|
|
||||||
(async () => {
|
|
||||||
const start = new Date();
|
|
||||||
for (let i = 0; i < 100; i += 1) {
|
|
||||||
const plots = plot(radarData, ['REF', 'VEL'], {
|
|
||||||
size,
|
|
||||||
palettize: true,
|
|
||||||
cropTo: size / 2,
|
|
||||||
});
|
|
||||||
|
|
||||||
// write files to disk
|
|
||||||
const writePromises = [];
|
|
||||||
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(`Total Time: ${(end - start) / 1000}`);
|
|
||||||
})();
|
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
/* eslint-disable no-console */
|
||||||
|
/* eslint-disable no-await-in-loop */
|
||||||
|
import Level2Radar from 'nexrad-level-2-data';
|
||||||
|
|
||||||
|
// eslint-disable-next-line import-x/no-extraneous-dependencies
|
||||||
|
import { glob } from 'glob';
|
||||||
|
import fs from 'node:fs';
|
||||||
|
import { plot, writePngToFile } from '../src/index.mjs';
|
||||||
|
|
||||||
|
// 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) => {
|
||||||
|
// eslint-disable-next-line n/no-sync
|
||||||
|
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
|
||||||
|
|
||||||
|
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 = [];
|
||||||
|
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`);
|
||||||
|
}
|
||||||
@@ -1,18 +1,20 @@
|
|||||||
const { Level2Radar } = require('nexrad-level-2-data');
|
/* eslint-disable no-console */
|
||||||
// eslint-disable-next-line import/no-extraneous-dependencies
|
import Level2Radar from 'nexrad-level-2-data';
|
||||||
const glob = require('glob');
|
|
||||||
const fs = require('fs');
|
|
||||||
|
|
||||||
const { plot, writePngToFile } = require('../src');
|
// eslint-disable-next-line import-x/no-extraneous-dependencies
|
||||||
|
import { glob } from 'glob';
|
||||||
|
import fs from 'node:fs';
|
||||||
|
|
||||||
|
import { plot, writePngToFile } from '../src/index.mjs';
|
||||||
|
|
||||||
// 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 = await 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/168/*');
|
||||||
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
|
||||||
@@ -20,6 +22,7 @@ const chunks = [];
|
|||||||
|
|
||||||
// parse each file
|
// parse each file
|
||||||
files.forEach((file) => {
|
files.forEach((file) => {
|
||||||
|
// eslint-disable-next-line n/no-sync
|
||||||
const fileBuffer = fs.readFileSync(file);
|
const fileBuffer = fs.readFileSync(file);
|
||||||
chunks.push(new Level2Radar(fileBuffer));
|
chunks.push(new Level2Radar(fileBuffer));
|
||||||
});
|
});
|
||||||
@@ -41,22 +44,24 @@ if (single) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// plot for each elevation and size
|
// plot for each elevation and size
|
||||||
(async () => {
|
console.time('processing');
|
||||||
await Promise.allSettled(sizes.map(async (size) => {
|
await Promise.allSettled(sizes.map(async (size) => {
|
||||||
const plots = plot(radarData, ['REF', 'VEL'], {
|
const plots = plot(radarData, ['REF', 'VEL'], {
|
||||||
elevations,
|
elevations,
|
||||||
size,
|
size,
|
||||||
palettize: true,
|
palettize: true,
|
||||||
cropTo: size / 2,
|
cropTo: size / 2,
|
||||||
});
|
imageSmoothingEnabled: false,
|
||||||
|
antialias: 'none',
|
||||||
|
});
|
||||||
|
|
||||||
// write files to disk
|
// write files to disk
|
||||||
const writePromises = [];
|
const writePromises = [];
|
||||||
plots.forEach((p) => {
|
plots.forEach((p) => {
|
||||||
const { elevation } = p;
|
const { elevation } = p;
|
||||||
writePromises.push(writePngToFile(`./output/REF-${elevation}-${size}.png`, p.REF));
|
writePromises.push(writePngToFile(`./output/REF-${elevation}-${size}.png`, p.REF));
|
||||||
writePromises.push(writePngToFile(`./output/VEL-${elevation}-${size}.png`, p.VEL));
|
writePromises.push(writePngToFile(`./output/VEL-${elevation}-${size}.png`, p.VEL));
|
||||||
});
|
});
|
||||||
await Promise.allSettled(writePromises);
|
await Promise.allSettled(writePromises);
|
||||||
}));
|
}));
|
||||||
})();
|
console.timeEnd('processing');
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
import path from 'node:path';
|
||||||
|
|
||||||
|
import { includeIgnoreFile } from '@eslint/compat';
|
||||||
|
import js from '@eslint/js';
|
||||||
|
import { defineConfig } from 'eslint/config';
|
||||||
|
import { configs, plugins } from 'eslint-config-airbnb-extended';
|
||||||
|
|
||||||
|
const gitignorePath = path.resolve('.', '.gitignore');
|
||||||
|
|
||||||
|
const jsConfig = defineConfig([
|
||||||
|
// ESLint recommended config
|
||||||
|
{
|
||||||
|
name: 'js/config',
|
||||||
|
...js.configs.recommended,
|
||||||
|
},
|
||||||
|
// Stylistic plugin
|
||||||
|
plugins.stylistic,
|
||||||
|
// Import X plugin
|
||||||
|
plugins.importX,
|
||||||
|
// Airbnb base recommended config
|
||||||
|
...configs.base.recommended,
|
||||||
|
]);
|
||||||
|
|
||||||
|
const nodeConfig = defineConfig([
|
||||||
|
// Node plugin
|
||||||
|
plugins.node,
|
||||||
|
// Airbnb Node recommended config
|
||||||
|
...configs.node.recommended,
|
||||||
|
]);
|
||||||
|
|
||||||
|
const rules = {
|
||||||
|
'@stylistic/indent': ['error', 'tab', { SwitchCase: 1 }],
|
||||||
|
'@stylistic/no-tabs': 0,
|
||||||
|
'no-param-reassign': [
|
||||||
|
'error',
|
||||||
|
{
|
||||||
|
props: false,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
'@stylistic/max-len': 0,
|
||||||
|
'no-underscore-dangle': [
|
||||||
|
'error',
|
||||||
|
{
|
||||||
|
allowAfterThis: true,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
'import-x/no-useless-path-segments': 0,
|
||||||
|
'no-bitwise': 0,
|
||||||
|
'import-x/extensions': [
|
||||||
|
'error',
|
||||||
|
'ignorePackages',
|
||||||
|
{
|
||||||
|
js: 'always',
|
||||||
|
mjs: 'always',
|
||||||
|
json: 'always',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
const languageOptions = {
|
||||||
|
ecmaVersion: 'latest',
|
||||||
|
parserOptions: {
|
||||||
|
ecmaVersion: 'latest',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const ignores = [
|
||||||
|
'docs/**',
|
||||||
|
];
|
||||||
|
|
||||||
|
export default defineConfig([
|
||||||
|
{
|
||||||
|
ignores,
|
||||||
|
},
|
||||||
|
// Ignore files and folders listed in .gitignore
|
||||||
|
includeIgnoreFile(gitignorePath),
|
||||||
|
// JavaScript config
|
||||||
|
...jsConfig,
|
||||||
|
// Node config
|
||||||
|
...nodeConfig,
|
||||||
|
{
|
||||||
|
languageOptions,
|
||||||
|
rules,
|
||||||
|
},
|
||||||
|
]);
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
{
|
||||||
|
"folders": [
|
||||||
|
{
|
||||||
|
"path": "."
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"settings": {}
|
||||||
|
}
|
||||||
Generated
+6134
-3782
File diff suppressed because it is too large.
Load diff
+40
-37
@@ -1,39 +1,42 @@
|
|||||||
{
|
{
|
||||||
"name": "nexrad-level-2-plot",
|
"name": "nexrad-level-2-plot",
|
||||||
"version": "2.2.0",
|
"version": "3.0.3",
|
||||||
"description": "Plotting library for nexrad-level-2-data",
|
"description": "Plotting library for nexrad-level-2-data",
|
||||||
"main": "src/index.js",
|
"main": "src/index.mjs",
|
||||||
"scripts": {
|
"type": "module",
|
||||||
"test": "echo \"Error: no test specified\" && exit 1"
|
"scripts": {
|
||||||
},
|
"lint": "npx eslint .",
|
||||||
"repository": {
|
"lint:fix": "npx eslint . --fix"
|
||||||
"type": "git",
|
},
|
||||||
"url": "git+https://github.com/netbymatt/nexrad-level-2-plot.git"
|
"repository": {
|
||||||
},
|
"type": "git",
|
||||||
"keywords": [
|
"url": "git+https://github.com/netbymatt/nexrad-level-2-plot.git"
|
||||||
"NEXRAD",
|
},
|
||||||
"level",
|
"keywords": [
|
||||||
"2",
|
"NEXRAD",
|
||||||
"radar",
|
"level",
|
||||||
"plot"
|
"2",
|
||||||
],
|
"radar",
|
||||||
"author": "Matt Walsh",
|
"plot"
|
||||||
"license": "MIT",
|
],
|
||||||
"bugs": {
|
"author": "Matt Walsh",
|
||||||
"url": "https://github.com/netbymatt/nexrad-level-2-plot/issues"
|
"license": "MIT",
|
||||||
},
|
"bugs": {
|
||||||
"homepage": "https://github.com/netbymatt/nexrad-level-2-plot#readme",
|
"url": "https://github.com/netbymatt/nexrad-level-2-plot/issues"
|
||||||
"dependencies": {
|
},
|
||||||
"canvas": "^2.8.0",
|
"homepage": "https://github.com/netbymatt/nexrad-level-2-plot#readme",
|
||||||
"nexrad-level-2-data": "^2.1.0"
|
"dependencies": {
|
||||||
},
|
"canvas": "^3.0.0",
|
||||||
"devDependencies": {
|
"nexrad-level-2-data": "^3.0.2"
|
||||||
"eslint": "^8.0.0",
|
},
|
||||||
"eslint-config-airbnb-base": "^15.0.0",
|
"devDependencies": {
|
||||||
"eslint-plugin-import": "^2.23.4",
|
"@eslint/compat": "^2.1.0",
|
||||||
"glob": "^7.1.7"
|
"@eslint/js": "^9.39.5",
|
||||||
},
|
"eslint": "^9.39.5",
|
||||||
"engines": {
|
"eslint-config-airbnb-extended": "^3.1.1",
|
||||||
"node": ">=13.0.0"
|
"glob": "^13.0.6"
|
||||||
}
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=24.0.0"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,15 +1,19 @@
|
|||||||
const canvasObj = require('canvas');
|
import canvasObj from 'canvas';
|
||||||
|
|
||||||
const { createCanvas } = canvasObj;
|
import Palette from './palettes/index.mjs';
|
||||||
|
|
||||||
const Palette = require('./palettes');
|
import palettizeImage from './palettize.mjs';
|
||||||
const palettizeImage = require('./palettize');
|
|
||||||
|
|
||||||
// data pre-processing
|
// data pre-processing
|
||||||
const filterProduct = require('./preprocess/filterproduct');
|
import filterProduct from './preprocess/filterproduct.mjs';
|
||||||
const downSample = require('./preprocess/downsample');
|
import downSample from './preprocess/downsample.mjs';
|
||||||
const indexProduct = require('./preprocess/indexproduct');
|
import indexProduct from './preprocess/indexproduct.mjs';
|
||||||
const rrle = require('./preprocess/rrle');
|
import rrle from './preprocess/rrle.mjs';
|
||||||
|
|
||||||
|
import * as ref from './palettes/ref.mjs';
|
||||||
|
import * as vel from './palettes/vel.mjs';
|
||||||
|
|
||||||
|
const { createCanvas } = canvasObj;
|
||||||
|
|
||||||
// names of data structures keyed to product name
|
// names of data structures keyed to product name
|
||||||
const dataNames = {
|
const dataNames = {
|
||||||
@@ -28,12 +32,11 @@ const dataFunctions = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// generate all palettes
|
// generate all palettes
|
||||||
/* eslint-disable global-require */
|
|
||||||
const palettes = {
|
const palettes = {
|
||||||
REF: new Palette(require('./palettes/ref')),
|
REF: new Palette(ref),
|
||||||
VEL: new Palette(require('./palettes/vel')),
|
VEL: new Palette(vel),
|
||||||
};
|
};
|
||||||
/* eslint-enable global-require */
|
|
||||||
|
|
||||||
const preferredWaveformUsage = {
|
const preferredWaveformUsage = {
|
||||||
1: ['REF', 'SW ', 'ZDR', 'PHI', 'RHO'],
|
1: ['REF', 'SW ', 'ZDR', 'PHI', 'RHO'],
|
||||||
@@ -51,6 +54,9 @@ const DEFAULT_OPTIONS = {
|
|||||||
background: 'black',
|
background: 'black',
|
||||||
lineWidth: 2,
|
lineWidth: 2,
|
||||||
usePreferredWaveforms: true,
|
usePreferredWaveforms: true,
|
||||||
|
alpha: true,
|
||||||
|
imageSmoothingEnabled: true,
|
||||||
|
antialias: 'default',
|
||||||
};
|
};
|
||||||
|
|
||||||
const draw = (data, _options) => {
|
const draw = (data, _options) => {
|
||||||
@@ -73,21 +79,28 @@ const draw = (data, _options) => {
|
|||||||
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 or 0.30km
|
||||||
|
// 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 gateSizeScaling = rawGateSize / 0.25;
|
||||||
|
|
||||||
// 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 and context
|
// create the canvas and context
|
||||||
const canvas = createCanvas(cropTo, cropTo);
|
const canvas = createCanvas(cropTo, cropTo);
|
||||||
const ctx = canvas.getContext('2d');
|
const ctx = canvas.getContext('2d', { alpha: options.alpha });
|
||||||
|
ctx.antialias = options.antialias;
|
||||||
|
ctx.imageSmoothingEnabled = options.imageSmoothingEnabled;
|
||||||
|
|
||||||
// fill background with black
|
// fill background with black
|
||||||
ctx.fillStyle = options.background;
|
ctx.fillStyle = options.background;
|
||||||
ctx.fillRect(0, 0, cropTo, cropTo);
|
ctx.fillRect(0, 0, cropTo, cropTo);
|
||||||
|
|
||||||
// canvas settings
|
// canvas settings
|
||||||
ctx.imageSmoothingEnabled = true;
|
// ctx.imageSmoothingEnabled = true;
|
||||||
ctx.lineWidth = options.lineWidth;
|
ctx.lineWidth = options.lineWidth / gateSizeScaling;
|
||||||
ctx.translate(cropTo / 2, cropTo / 2);
|
ctx.translate(cropTo / 2, cropTo / 2);
|
||||||
ctx.rotate(-Math.PI / 2);
|
ctx.rotate(-Math.PI / 2);
|
||||||
|
|
||||||
@@ -125,6 +138,21 @@ const draw = (data, _options) => {
|
|||||||
const rrlEncoded = rrle(indexedProduct, resolution);
|
const rrlEncoded = rrle(indexedProduct, resolution);
|
||||||
|
|
||||||
// loop through data
|
// loop through data
|
||||||
|
// bins are drawn in the same order as before (radials in azimuth order, then
|
||||||
|
// range bins outward) but a stroke() + beginPath() pair is only expensive to
|
||||||
|
// issue once per arc, and most of that cost is fixed overhead independent of
|
||||||
|
// arc size. so instead of stroking every single bin individually, consecutive
|
||||||
|
// bins that share the same color are accumulated into one path and painted
|
||||||
|
// with a single stroke() call. this never reorders anything relative to the
|
||||||
|
// original drawing sequence, it just defers the stroke() until the color is
|
||||||
|
// about to change (or the data runs out), so the result is unaffected other
|
||||||
|
// than by output speed.
|
||||||
|
let openStrokeStyle = null;
|
||||||
|
const flushStroke = () => {
|
||||||
|
if (openStrokeStyle === null) return;
|
||||||
|
ctx.stroke();
|
||||||
|
};
|
||||||
|
|
||||||
rrlEncoded.forEach((radial) => {
|
rrlEncoded.forEach((radial) => {
|
||||||
// calculate plotting parameters
|
// calculate plotting parameters
|
||||||
const deadZone = radial.first_gate / radial.gate_size / scale;
|
const deadZone = radial.first_gate / radial.gate_size / scale;
|
||||||
@@ -134,23 +162,45 @@ const draw = (data, _options) => {
|
|||||||
const endAngle = radial.azimuth * (Math.PI / 180) + halfResolution * 1.1;
|
const endAngle = radial.azimuth * (Math.PI / 180) + halfResolution * 1.1;
|
||||||
|
|
||||||
// plot each bin
|
// plot each bin
|
||||||
radial.moment_data.forEach((bin, idx) => {
|
// (a plain for loop avoids per-bin callback-invocation overhead - this runs
|
||||||
|
// up to ~radials x gates times per elevation/product)
|
||||||
|
const { moment_data: momentData } = radial;
|
||||||
|
for (let idx = 0; idx < momentData.length; idx += 1) {
|
||||||
|
const bin = momentData[idx];
|
||||||
if (bin !== null) {
|
if (bin !== null) {
|
||||||
ctx.beginPath();
|
|
||||||
// different methods for rrle encoded or not
|
// different methods for rrle encoded or not
|
||||||
|
let color;
|
||||||
|
let arcEndAngle;
|
||||||
if (bin.count) {
|
if (bin.count) {
|
||||||
// rrle encoded
|
// rrle encoded
|
||||||
ctx.strokeStyle = palette.lookupRgba[bin.value];
|
color = palette.lookupRgba[bin.value];
|
||||||
ctx.arc(0, 0, (idx + deadZone), startAngle, endAngle + resolution * (bin.count - 1));
|
arcEndAngle = endAngle + resolution * (bin.count - 1);
|
||||||
} else {
|
} else {
|
||||||
// plain data
|
// plain data
|
||||||
ctx.strokeStyle = palette.lookupRgba[bin];
|
color = palette.lookupRgba[bin];
|
||||||
ctx.arc(0, 0, (idx + deadZone), startAngle, endAngle);
|
arcEndAngle = endAngle;
|
||||||
}
|
}
|
||||||
ctx.stroke();
|
|
||||||
|
// paint and close out the prior path whenever the color changes, since a
|
||||||
|
// single stroke() call can only use one strokeStyle
|
||||||
|
if (color !== openStrokeStyle) {
|
||||||
|
flushStroke();
|
||||||
|
ctx.beginPath();
|
||||||
|
ctx.strokeStyle = color;
|
||||||
|
openStrokeStyle = color;
|
||||||
|
}
|
||||||
|
|
||||||
|
const radius = (idx + deadZone) * gateSizeScaling;
|
||||||
|
// moveTo to the arc's start point first so this arc becomes its own
|
||||||
|
// subpath rather than getting connected to the previous arc by a
|
||||||
|
// straight line (canvas connects consecutive arc() calls otherwise)
|
||||||
|
ctx.moveTo(radius * Math.cos(startAngle), radius * Math.sin(startAngle));
|
||||||
|
ctx.arc(0, 0, radius, startAngle, arcEndAngle);
|
||||||
}
|
}
|
||||||
});
|
}
|
||||||
});
|
});
|
||||||
|
// paint whatever is left in the final open path
|
||||||
|
flushStroke();
|
||||||
|
|
||||||
if (!options.palettize) {
|
if (!options.palettize) {
|
||||||
// return the palette and canvas
|
// return the palette and canvas
|
||||||
@@ -160,7 +210,7 @@ const draw = (data, _options) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// palettize image
|
// palettize image
|
||||||
const palettized = palettizeImage(canvas.getContext('2d'), palette);
|
const palettized = palettizeImage(ctx, palette);
|
||||||
|
|
||||||
// return palettized image
|
// return palettized image
|
||||||
return {
|
return {
|
||||||
@@ -169,8 +219,10 @@ const draw = (data, _options) => {
|
|||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
module.exports = {
|
const canvas = canvasObj;
|
||||||
|
|
||||||
|
export {
|
||||||
draw,
|
draw,
|
||||||
DEFAULT_OPTIONS,
|
DEFAULT_OPTIONS,
|
||||||
canvas: canvasObj,
|
canvas,
|
||||||
};
|
};
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
const RGBA_LOOKUP_SIZE = 200;
|
||||||
|
|
||||||
|
// create a lookup table for indices generated by findDbzIndexGenerator
|
||||||
|
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 = [];
|
||||||
|
for (let i = -RGBA_LOOKUP_SIZE; i <= RGBA_LOOKUP_SIZE; i += 1) {
|
||||||
|
let index = limits.findIndex((limit) => i < limit);
|
||||||
|
// a value of -1 means it is off the end of the scale, set to highest value
|
||||||
|
if (index === -1) index = maxDbzIndex;
|
||||||
|
lookupRgba.push(index);
|
||||||
|
}
|
||||||
|
return lookupRgba;
|
||||||
|
};
|
||||||
|
|
||||||
|
const downSample = (cur, prev) => (cur === null ? prev : Math.max(cur, prev));
|
||||||
|
|
||||||
|
const inDeadband = (reset) => (a) => (a === null || a === reset || a === undefined);
|
||||||
|
|
||||||
|
export {
|
||||||
|
findDbzIndexGenerator,
|
||||||
|
findDbzRbgaGenerator,
|
||||||
|
downSample,
|
||||||
|
inDeadband,
|
||||||
|
RGBA_LOOKUP_SIZE,
|
||||||
|
};
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
const hexLookup = ['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'];
|
||||||
|
export default hexLookup;
|
||||||
@@ -4,7 +4,10 @@
|
|||||||
// 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 rgbaLookupSize = 200;
|
import hexLookup from './hexlookup.mjs';
|
||||||
|
import {
|
||||||
|
findDbzIndexGenerator, findDbzRbgaGenerator, downSample, inDeadband, RGBA_LOOKUP_SIZE,
|
||||||
|
} from './helpers.mjs';
|
||||||
|
|
||||||
class Palette {
|
class Palette {
|
||||||
constructor(palette) {
|
constructor(palette) {
|
||||||
@@ -16,7 +19,7 @@ class Palette {
|
|||||||
this.closest = {};
|
this.closest = {};
|
||||||
|
|
||||||
// these may not exist and are overridden with default functions
|
// these may not exist and are overridden with default functions
|
||||||
if (palette.hasOwnProperty('downSampleReset')) {
|
if (Object.hasOwn(palette, 'downSampleReset')) {
|
||||||
this.downSampleReset = palette.downSampleReset;
|
this.downSampleReset = palette.downSampleReset;
|
||||||
} else {
|
} else {
|
||||||
this.downSampleReset = -Infinity;
|
this.downSampleReset = -Infinity;
|
||||||
@@ -36,7 +39,7 @@ class Palette {
|
|||||||
|
|
||||||
findColorIndex(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.lookupIndex[Math.trunc(dbz + rgbaLookupSize)];
|
return this.lookupIndex[Math.trunc(dbz + RGBA_LOOKUP_SIZE)];
|
||||||
}
|
}
|
||||||
|
|
||||||
getPalette() {
|
getPalette() {
|
||||||
@@ -54,19 +57,20 @@ class Palette {
|
|||||||
return `rgba(${this.palette[index * 4]},${this.palette[index * 4 + 1]},${this.palette[index * 4 + 2]},${this.palette[(index * 4 + 3)] / 255})`;
|
return `rgba(${this.palette[index * 4]},${this.palette[index * 4 + 1]},${this.palette[index * 4 + 2]},${this.palette[(index * 4 + 3)] / 255})`;
|
||||||
}
|
}
|
||||||
|
|
||||||
// match = [r,g,b[,a]]
|
// r,g,b = individual color components, passed separately to avoid allocating
|
||||||
closestIndex(match) {
|
// a temporary array for every pixel (this is called once per output pixel)
|
||||||
|
closestIndex(r, g, b) {
|
||||||
// short circuit for transparent (black)
|
// short circuit for transparent (black)
|
||||||
if (match[0] <= 2 && match[1] <= 2 && match[2] <= 2) return this.transparentIndex;
|
if (r <= 2 && g <= 2 && b <= 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[r] + hexLookup[g] + hexLookup[b];
|
||||||
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;
|
||||||
let closest = Infinity;
|
let closest = Infinity;
|
||||||
// loop through array
|
// loop through array
|
||||||
for (let i = 0; i < this.palette.length; i += 4) {
|
for (let i = 0; i < this.palette.length; i += 4) {
|
||||||
const dist = Palette.geometricDistance(match, this.palette.slice(i, i + match.length));
|
const dist = Palette.geometricDistance(r, g, b, this.palette[i], this.palette[i + 1], this.palette[i + 2]);
|
||||||
// test for closer
|
// test for closer
|
||||||
if (dist < closest) {
|
if (dist < closest) {
|
||||||
closest = dist;
|
closest = dist;
|
||||||
@@ -80,34 +84,10 @@ class Palette {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// geometric distance
|
// geometric distance
|
||||||
static geometricDistance(a, b) {
|
// square root is intentionally not taken for performance reasons
|
||||||
return a.reduce((acc, val, idx) => acc + (val - b[idx]) ** 2, 0);
|
static geometricDistance(r1, g1, b1, r2, g2, b2) {
|
||||||
|
return (r1 - r2) ** 2 + (g1 - g2) ** 2 + (b1 - b2) ** 2;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// create a lookup table for indices generated by findDbzIndexGenerator
|
export default Palette;
|
||||||
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 = [];
|
|
||||||
for (let i = -rgbaLookupSize; i <= rgbaLookupSize; i += 1) {
|
|
||||||
let index = limits.findIndex((limit) => i < limit);
|
|
||||||
// a value of -1 means it is off the end of the scale, set to highest value
|
|
||||||
if (index === -1) index = maxDbzIndex;
|
|
||||||
lookupRgba.push(index);
|
|
||||||
}
|
|
||||||
return lookupRgba;
|
|
||||||
};
|
|
||||||
|
|
||||||
const downSample = (cur, prev) => (cur === null ? prev : Math.max(cur, prev));
|
|
||||||
|
|
||||||
const inDeadband = (reset) => (a) => (a === null || a === reset || a === undefined);
|
|
||||||
|
|
||||||
module.exports = Palette;
|
|
||||||
@@ -34,11 +34,11 @@ const palette = [
|
|||||||
|
|
||||||
const maxDbzIndex = 14; // index of maximum dbz
|
const maxDbzIndex = 14; // index of maximum dbz
|
||||||
|
|
||||||
const limits = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75];
|
const limits = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75];
|
||||||
|
|
||||||
const transparentIndex = 0;
|
const transparentIndex = 0;
|
||||||
|
|
||||||
module.exports = {
|
export {
|
||||||
palette,
|
palette,
|
||||||
maxDbzIndex,
|
maxDbzIndex,
|
||||||
limits,
|
limits,
|
||||||
@@ -41,7 +41,7 @@ const downSample = (cur, prev) => {
|
|||||||
return prev;
|
return prev;
|
||||||
};
|
};
|
||||||
|
|
||||||
const limits = [-99, -90, -80, -70, -60, -50, -40, -30, -20, -15, -10, -5, 0, 5, 10, 15, 20, 30, 40, 50, 60, 70, 80, 90, 99,
|
const limits = [-99, -90, -80, -70, -60, -50, -40, -30, -20, -15, -10, -5, 0, 5, 10, 15, 20, 30, 40, 50, 60, 70, 80, 90, 99,
|
||||||
];
|
];
|
||||||
|
|
||||||
const downSampleReset = null;
|
const downSampleReset = null;
|
||||||
@@ -50,7 +50,7 @@ const maxDbzIndex = 12; // index of maximum dbz
|
|||||||
|
|
||||||
const transparentIndex = 24;
|
const transparentIndex = 24;
|
||||||
|
|
||||||
module.exports = {
|
export {
|
||||||
palette,
|
palette,
|
||||||
downSample,
|
downSample,
|
||||||
limits,
|
limits,
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
const { createCanvas } = require('canvas');
|
import { createCanvas } from 'canvas';
|
||||||
|
|
||||||
const palettizeImage = (sourceCtx, palette) => {
|
const palettizeImage = (sourceCtx, palette) => {
|
||||||
// get the dimensions of the image from the ctx
|
// get the dimensions of the image from the ctx
|
||||||
@@ -13,14 +13,17 @@ const palettizeImage = (sourceCtx, palette) => {
|
|||||||
const indexedCtx = indexedCanvas.getContext('2d', { pixelFormat: 'A8' });
|
const indexedCtx = indexedCanvas.getContext('2d', { pixelFormat: 'A8' });
|
||||||
|
|
||||||
// get the source image data
|
// get the source image data
|
||||||
const sourceImageData = sourceCtx.getImageData(0, 0, dim.x, dim.y);
|
const { data: sourceData } = sourceCtx.getImageData(0, 0, dim.x, dim.y);
|
||||||
// get the indexed image data (destination)
|
// get the indexed image data (destination)
|
||||||
const indexedImageData = indexedCtx.getImageData(0, 0, dim.x, dim.y);
|
const indexedImageData = indexedCtx.getImageData(0, 0, dim.x, dim.y);
|
||||||
|
const { data: indexedData } = indexedImageData;
|
||||||
|
|
||||||
// loop through each pixel
|
// loop through each pixel
|
||||||
indexedImageData.data.forEach((val, idx) => {
|
// (a plain for loop indexing directly into the source data avoids allocating
|
||||||
indexedImageData.data[idx] = palette.closestIndex(sourceImageData.data.slice(idx * 4, idx * 4 + 3));
|
// a new typed array per pixel, which a .slice()-based approach would require)
|
||||||
});
|
for (let idx = 0, srcIdx = 0; idx < indexedData.length; idx += 1, srcIdx += 4) {
|
||||||
|
indexedData[idx] = palette.closestIndex(sourceData[srcIdx], sourceData[srcIdx + 1], sourceData[srcIdx + 2]);
|
||||||
|
}
|
||||||
|
|
||||||
// write the new image data
|
// write the new image data
|
||||||
indexedCtx.putImageData(indexedImageData, 0, 0);
|
indexedCtx.putImageData(indexedImageData, 0, 0);
|
||||||
@@ -28,4 +31,4 @@ const palettizeImage = (sourceCtx, palette) => {
|
|||||||
return indexedCanvas;
|
return indexedCanvas;
|
||||||
};
|
};
|
||||||
|
|
||||||
module.exports = palettizeImage;
|
export default palettizeImage;
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
// this includes "cropping" the data to the specified size
|
// this includes "cropping" the data to the specified size
|
||||||
|
|
||||||
// calculation constants
|
// calculation constants
|
||||||
const RAD45 = (45 * Math.PI / 180);
|
const RAD45 = (45 * Math.PI) / 180;
|
||||||
const RAD90 = RAD45 * 2;
|
const RAD90 = RAD45 * 2;
|
||||||
|
|
||||||
const downSample = (radials, scale, resolution, options, palette) => {
|
const downSample = (radials, scale, resolution, options, palette) => {
|
||||||
@@ -25,7 +25,7 @@ const downSample = (radials, scale, resolution, options, palette) => {
|
|||||||
const azWrap = (((azimuth - RAD45) % RAD90) + RAD90) % RAD90;
|
const azWrap = (((azimuth - RAD45) % RAD90) + RAD90) % RAD90;
|
||||||
// calculate a magnitude multiplier as 1/sin with 45° shift removed
|
// calculate a magnitude multiplier as 1/sin with 45° shift removed
|
||||||
const azMagnitudeMult = 1 / Math.abs(Math.sin(azWrap + RAD45));
|
const azMagnitudeMult = 1 / Math.abs(Math.sin(azWrap + RAD45));
|
||||||
const cropMaxBin = Math.ceil(Math.abs(options.cropTo / 2 * scale * azMagnitudeMult));
|
const cropMaxBin = Math.ceil(Math.abs((options.cropTo / 2) * scale * azMagnitudeMult));
|
||||||
|
|
||||||
// compare max calculated value with length of radial
|
// compare max calculated value with length of radial
|
||||||
const maxBin = Math.min(cropMaxBin, radial.moment_data.length);
|
const maxBin = Math.min(cropMaxBin, radial.moment_data.length);
|
||||||
@@ -53,4 +53,4 @@ const downSample = (radials, scale, resolution, options, palette) => {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
module.exports = downSample;
|
export default downSample;
|
||||||
@@ -13,4 +13,4 @@ const filterProduct = (data, product) => data.map((header) => {
|
|||||||
// remove any missing radials
|
// remove any missing radials
|
||||||
}).filter((d) => d);
|
}).filter((d) => d);
|
||||||
|
|
||||||
module.exports = filterProduct;
|
export default filterProduct;
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
// 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;
|
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
// 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) => {
|
||||||
|
// a plain for loop avoids per-bin callback-invocation overhead here - this
|
||||||
|
// runs up to ~radials x gates times per elevation/product
|
||||||
|
const { moment_data: momentData } = radial;
|
||||||
|
const indexedMoment = new Array(momentData.length);
|
||||||
|
for (let idx = 0; idx < momentData.length; idx += 1) {
|
||||||
|
const bin = momentData[idx];
|
||||||
|
if (bin === null || palette.inDeadband(bin)) {
|
||||||
|
indexedMoment[idx] = null;
|
||||||
|
} else {
|
||||||
|
indexedMoment[idx] = palette.findColorIndex(bin);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
...radial,
|
||||||
|
moment_data: indexedMoment,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
export default indexProduct;
|
||||||
@@ -4,8 +4,6 @@
|
|||||||
const findTotalMatches = (radials, startI, binIdx, resolutionThreshold) => {
|
const findTotalMatches = (radials, startI, binIdx, resolutionThreshold) => {
|
||||||
// get the target value
|
// get the target value
|
||||||
const target = radials[startI].moment_data[binIdx];
|
const target = radials[startI].moment_data[binIdx];
|
||||||
// check for null
|
|
||||||
if (target === null) return false;
|
|
||||||
|
|
||||||
// start a counter for matches
|
// start a counter for matches
|
||||||
let count = 1;
|
let count = 1;
|
||||||
@@ -23,7 +21,7 @@ const findTotalMatches = (radials, startI, binIdx, resolutionThreshold) => {
|
|||||||
// end condition is the number of radials available
|
// end condition is the number of radials available
|
||||||
// a radial not within the resolution threshold
|
// a radial not within the resolution threshold
|
||||||
// or the binIdx under test not present in one of the next radials
|
// or the binIdx under test not present in one of the next radials
|
||||||
while (nextI < radials.length && checkNext) {
|
while (checkNext && nextI < radials.length) {
|
||||||
// reset flag
|
// reset flag
|
||||||
checkNext = false;
|
checkNext = false;
|
||||||
const nextAzimuth = radials[nextI].azimuth;
|
const nextAzimuth = radials[nextI].azimuth;
|
||||||
@@ -48,7 +46,7 @@ const findTotalMatches = (radials, startI, binIdx, resolutionThreshold) => {
|
|||||||
|
|
||||||
const rrle = (radials, resolutionRad) => {
|
const rrle = (radials, resolutionRad) => {
|
||||||
// calculate the nominal angle to the next radial plus 20% to easily account for floating point inaccuracies
|
// 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;
|
const resolutionThreshold = ((resolutionRad * 180) / Math.PI) * 1.2;
|
||||||
// sort the radials by azimuth, 0 > 360
|
// sort the radials by azimuth, 0 > 360
|
||||||
const sorted = radials.sort((a, b) => a.azimuth - b.azimuth);
|
const sorted = radials.sort((a, b) => a.azimuth - b.azimuth);
|
||||||
|
|
||||||
@@ -60,13 +58,14 @@ const rrle = (radials, resolutionRad) => {
|
|||||||
|
|
||||||
// look at each bin on the radial
|
// look at each bin on the radial
|
||||||
radial.moment_data.forEach((bin, binIdx) => {
|
radial.moment_data.forEach((bin, binIdx) => {
|
||||||
|
if (radials[i].moment_data[binIdx] === null) return;
|
||||||
const totalMatches = findTotalMatches(radials, i, binIdx, resolutionThreshold);
|
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 a total match was found update the bin data and null out the remaining bins in the run
|
||||||
if (totalMatches) {
|
if (!totalMatches) return;
|
||||||
radial.moment_data[binIdx] = { value: bin, count: totalMatches };
|
radial.moment_data[binIdx] = { value: bin, count: totalMatches };
|
||||||
for (let clearI = i + 1; clearI <= i + totalMatches - 1; clearI += 1) {
|
const loopEnd = i + totalMatches - 1;
|
||||||
sorted[clearI].moment_data[binIdx] = null;
|
for (let clearI = i + 1; clearI <= loopEnd; clearI += 1) {
|
||||||
}
|
sorted[clearI].moment_data[binIdx] = null;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -74,4 +73,4 @@ const rrle = (radials, resolutionRad) => {
|
|||||||
return radials;
|
return radials;
|
||||||
};
|
};
|
||||||
|
|
||||||
module.exports = rrle;
|
export default rrle;
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
const { draw, canvas } = require('./draw');
|
import { draw, canvas } from './draw/index.mjs';
|
||||||
const { writePngToFile } = require('./utils/file');
|
import writePngToFile from './utils/writePngToFile.mjs';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 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
|
||||||
@@ -12,6 +13,9 @@ const { writePngToFile } = require('./utils/file');
|
|||||||
* @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 {(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.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 = (data, _products, options) => {
|
||||||
@@ -54,7 +58,9 @@ const plot = (data, _products, options) => {
|
|||||||
return result;
|
return result;
|
||||||
};
|
};
|
||||||
|
|
||||||
module.exports = {
|
export default plot;
|
||||||
|
|
||||||
|
export {
|
||||||
plot,
|
plot,
|
||||||
writePngToFile,
|
writePngToFile,
|
||||||
canvas,
|
canvas,
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
const fs = require('fs');
|
import fs from 'node:fs';
|
||||||
// write a canvas to a Png file
|
// write a canvas to a Png file
|
||||||
/**
|
/**
|
||||||
* Write a Canvas to the specified file
|
* Write a Canvas to the specified file
|
||||||
@@ -26,6 +26,4 @@ const writePngToFile = (fileName, data) => new Promise((resolve, reject) => {
|
|||||||
writeStream.on('error', (e) => reject(e));
|
writeStream.on('error', (e) => reject(e));
|
||||||
});
|
});
|
||||||
|
|
||||||
module.exports = {
|
export default writePngToFile;
|
||||||
writePngToFile,
|
|
||||||
};
|
|
||||||
Reference in new issue
Block a user