Compare commits

..
1 Commits
Author SHA1 Message Date
Matt Walsh 1b9a72ed99 convert to typescript 2021-08-26 15:42:24 -05:00
42 changed files with 6445 additions and 4525 deletions

No files matched your search

+62 -37
View File
@@ -1,19 +1,33 @@
module.exports = {
root: true,
env: {
browser: true,
commonjs: true,
node: true,
jquery: true,
},
extends: 'airbnb-base',
extends: [
'airbnb-base',
'plugin:@typescript-eslint/eslint-recommended',
'plugin:@typescript-eslint/recommended',
],
globals: {
Atomics: 'readonly',
SharedArrayBuffer: 'readonly',
},
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaVersion: 2020,
},
plugins: ['import'],
settings: {
'import/parsers': {
'@typescript-eslint/parser': ['.ts', '.tsx'],
},
'import/resolver': {
typescript: {
alwaysTryTypes: true,
},
},
},
rules: {
indent: [
'error',
@@ -25,12 +39,12 @@ module.exports = {
variables: false,
},
],
'no-param-reassign': [
'error',
{
props: false,
},
],
// 'no-param-reassign': [
// 'error',
// {
// props: false,
// },
// ],
'no-tabs': 0,
'no-console': 0,
'max-len': 0,
@@ -39,40 +53,51 @@ module.exports = {
'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': [
// 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,
'import/extensions': [
'error',
'ignorePackages',
{
groups: [
['&', '|', '^', '~', '<<', '>>', '>>>'],
['==', '!=', '===', '!==', '>', '>=', '<', '<='],
['&&', '||'],
['in', 'instanceof'],
],
allowSamePrecedence: true,
ts: 'never',
js: 'never',
},
],
'no-underscore-dangle': ['error', {
allowAfterThis: true,
}],
'no-bitwise': 0,
// the following are handled by the typescript parser
'lines-between-class-members': 'off',
},
ignorePatterns: [
'*.min.js',
'dist/**',
],
};
+16 -3
View File
@@ -11,16 +11,29 @@
"skipFiles": [
"<node_internals>/**"
],
"program": "${workspaceFolder}/demos/test.js"
"program": "${workspaceFolder}/dist/demos/test.js",
"preLaunchTask": "tsc: build - tsconfig.json",
"outFiles": [
"${workspaceFolder}/dist/**/*.js",
"!**/node_modules/**"
],
"internalConsoleOptions": "openOnSessionStart",
},
{
"type": "pwa-node",
"request": "launch",
"name": "Benchmark",
"name": "Test Single",
"skipFiles": [
"<node_internals>/**"
],
"program": "${workspaceFolder}/demos/benchmark.js"
"program": "${workspaceFolder}/dist/demos/test.js",
"preLaunchTask": "tsc: build - tsconfig.json",
"args": ["single"],
"outFiles": [
"${workspaceFolder}/dist/**/*.js",
"!**/node_modules/**"
],
"internalConsoleOptions": "openOnSessionStart"
}
]
}
+5 -5
View File
@@ -1,19 +1,19 @@
{
"files.exclude": {
"node_modules/nexrad-level-2-data/**/node_modules": true,
"**/node_modules": true
"**/node_modules": true,
"dist/**": true,
},
"cSpell.words": [
"KLOT",
"Mult",
"NOAA",
"Palettized",
"RGBA",
"Rbga",
"palettization",
"palettize",
"Palettized",
"palletizing",
"Rbga",
"RGBA",
"rrle",
"uncommenting"
]
}
+11 -30
View File
@@ -47,19 +47,15 @@ Test code and data is provided in the `./demo` folder. `test.js` can be used to
# API
## plot(data, products, options)
Returns an array of objects. The order of elevations in the returned array matches the order of elevations in options.elevations
Returns an object
``` javascript
[
{
elevation: <integer>,
REF: {
canvas: <Canvas>,
palette: <Uint8ClampedArray>
},
//... additional products
{
REF: {
canvas: <Canvas>,
palette: <Uint8ClampedArray>
},
// ... additional elevations
]
//... additional products
}
```
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.
@@ -77,15 +73,15 @@ 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.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.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.
### 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).
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() which will also be much faster than the drawing methods used for a radar 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().
options.crop
### 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.
@@ -94,7 +90,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.
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.
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.
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.
@@ -112,21 +108,6 @@ 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).
data|{canvas[palette]}|Typically the output of [plot()](#plotfile-options).\<product type>.
# Notable and breaking changes
## 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
The code for this project is based upon:
- [Unidata](https://github.com/Unidata/thredds/blob/master/cdm/src/main/java/ucar/nc2/iosp/nexrad2/)
-49
View File
@@ -1,49 +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;
const iterations = 10;
// 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,
});
// 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`);
}
})();
+56
View File
@@ -0,0 +1,56 @@
"use strict";
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('../index');
// list files
// const files = glob.sync('./data/KLOT/34/*');
// const files = glob.sync('./data/KLOT/381/*');
// const files = glob.sync('./data/KLOT/548/*');
// const files = glob.sync('./data/KLOT/940/*');
// const files = glob.sync('./data/KSRX/804/*');
// 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/KLOT20210621_041151_V06'); // vel 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);
// result array by elevations
const plots = [];
// default to all plots unless single is specificed
const single = process.argv.includes('single');
let sizes = [3600, 1800, 900, 800, 600, 450, 100];
let elevations = radarData.listElevations();
if (single) {
sizes = sizes.slice(0, 1);
// elevations where the lowest elevation is present, this is to ensure velocity is available
const firstElevationIndex = elevations.slice(0, 1)[0];
const lowestAngle = radarData.vcp.record.elevations[firstElevationIndex].elevation_angle;
elevations = elevations.filter((elevation) => radarData.vcp.record.elevations[elevation].elevation_angle === lowestAngle);
}
// plot for each elevation and size
(async () => {
await Promise.allSettled(sizes.map(async (size) => {
await Promise.allSettled(elevations.map(async (elevation) => {
plots[elevation] = plot(radarData, ['REF', 'VEL'], {
elevation,
size,
palettize: true,
cropTo: size / 2,
});
// write files to disk
await Promise.allSettled([
writePngToFile(`./output/REF-${elevation}-${size}.png`, plots[elevation].REF),
writePngToFile(`./output/VEL-${elevation}-${size}.png`, plots[elevation].VEL),
]);
}));
}));
})();
//# sourceMappingURL=test.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"test.js","sourceRoot":"","sources":["../../src/demos/test.js"],"names":[],"mappings":";AAAA,MAAM,EAAE,WAAW,EAAE,GAAG,OAAO,CAAC,qBAAqB,CAAC,CAAC;AACvD,6DAA6D;AAC7D,MAAM,IAAI,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;AAC7B,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;AAEzB,MAAM,EAAE,IAAI,EAAE,cAAc,EAAE,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;AAErD,aAAa;AACb,+CAA+C;AAC/C,gDAAgD;AAChD,gDAAgD;AAChD,gDAAgD;AAChD,gDAAgD;AAChD,gDAAgD;AAChD,MAAM,KAAK,GAAG,IAAI,CAAC,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AC1H;AAED,mCAAmC;AACnC,CAAC,KAAK,IAAI,EAAE;IACX,MAAM,OAAO,CAAC,UAAU,CAAC,KAAK,CAAC,GAAG,CAAC,KAAK,EAAE,IAAI,EAAE,EAAE;QACjD,MAAM,OAAO,CAAC,UAAU,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,EAAE,SAAS,EAAE,EAAE;YAC3D,KAAK,CAAC,SAAS,CAAC,GAAG,IAAI,CAAC,SAAS,EAAE,CAAC,KAAK,EAAE,KAAK,CAAC,EAAE;gBAClD,SAAS;gBACT,IAAI;gBACJ,SAAS,EAAE,IAAI;gBACf,MAAM,EAAE,IAAI,GAAG,CAAC;aAChB,CAAC,CAAC;YAEH,sBAAsB;YACtB,MAAM,OAAO,CAAC,UAAU,CAAC;gBACxB,cAAc,CAAC,gBAAgB,SAAS,IAAI,IAAI,MAAM,EAAE,KAAK,CAAC,SAAS,CAAC,CAAC,GAAG,CAAC;gBAC7E,cAAc,CAAC,gBAAgB,SAAS,IAAI,IAAI,MAAM,EAAE,KAAK,CAAC,SAAS,CAAC,CAAC,GAAG,CAAC;aAC7E,CAAC,CAAC;QACJ,CAAC,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,EAAE,CAAC"}
+170
View File
@@ -0,0 +1,170 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const canvas_1 = __importDefault(require("canvas"));
const palettes_1 = __importDefault(require("./palettes"));
const ref_1 = __importDefault(require("./palettes/ref"));
const vel_1 = __importDefault(require("./palettes/vel"));
const palettize_1 = __importDefault(require("./palettize"));
const { createCanvas } = canvas_1.default;
// names of data structures keyed to product name
const dataNames = {
REF: 'reflect',
VEL: 'velocity',
'SW ': 'spectrum',
ZDR: 'zdr',
PHI: 'phi',
RHO: 'rho',
};
// names of data retrieval routines keyed to product name
const dataFunctions = {
REF: 'getHighresReflectivity',
VEL: 'getHighresVelocity',
};
// generate all palettes
const palettes = {
REF: new palettes_1.default(ref_1.default),
VEL: new palettes_1.default(vel_1.default),
};
// default options
const DEFAULT_OPTIONS = {
// must be a square image
size: 3600,
cropTo: 3600,
background: 'black',
lineWidth: 2,
};
// calculation constants
const RAD45 = ((45 * Math.PI) / 180);
const RAD90 = RAD45 * 2;
const draw = (data, _options) => {
// combine options with defaults
const options = {
...DEFAULT_OPTIONS,
..._options,
};
// calculate scale
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');
const scale = DEFAULT_OPTIONS.size / options.size;
// calculate crop, adjust if necessary
const cropTo = Math.min(options.size, options.cropTo);
if (options.cropTo < 1)
throw new Error('Provide options.cropTo > 0');
// create the canvas and context
const canvas = createCanvas(cropTo, cropTo);
const ctx = canvas.getContext('2d');
// fill background with black
ctx.fillStyle = options.background;
ctx.fillRect(0, 0, cropTo, cropTo);
// canvas settings
ctx.imageSmoothingEnabled = true;
ctx.lineWidth = options.lineWidth;
ctx.translate(cropTo / 2, cropTo / 2);
ctx.rotate(-Math.PI / 2);
// get the palette
const palette = palettes[options.product];
// test for valid palette
if (!palette)
throw new Error(`No product found for product type: ${options.product}`);
// set the elevation
data.setElevation(options.elevation);
// get the header data
const headers = data.getHeader();
// calculate resolution in radians, default to 1°
let resolution = Math.PI / 180;
if (data?.vcp?.record?.elevation?.s[options.elevation]?.super_res_control?.super_res?.halfDegreeAzimuth)
resolution /= 2;
// calculate half resolution step for additional calculations below
const halfResolution = resolution / 2;
// match product name to data
const dataName = dataNames[options.product];
const dataFunction = dataFunctions[options.product];
// check for valid product
if (dataName === undefined)
throw new Error(`No data object name found for product: ${options.product}`);
if (dataFunction === undefined)
throw new Error(`No data function found for product: ${options.product}`);
// check for data for this product
if (headers[0][dataName] === undefined)
return false;
// loop through data
headers.forEach((header) => {
// get correct data
const thisRadial = header[dataName];
// skip if this radial isn't found
if (thisRadial === undefined)
return;
// calculate plotting parameters
const deadZone = thisRadial.first_gate / thisRadial.gate_size;
const startAngle = header.azimuth * (Math.PI / 180) - halfResolution;
const endAngle = startAngle + resolution;
// 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
for (let idx = 0; idx < maxBin; idx += 1) {
// get the value
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
downsampled = palette.downSample(bin, downsampled);
// store for rollover tracking
lastRemainder = remainder;
}
else {
thisSample = bin;
}
// see if there's a sample to plot
if (thisSample && !palette.inDeadband(thisSample)) {
ctx.beginPath();
ctx.strokeStyle = palette.findColorRgba(thisSample);
ctx.arc(0, 0, (idx + deadZone) / scale, startAngle, endAngle);
ctx.stroke();
}
}
}
});
if (!options.palettize) {
// return the palette and canvas
return {
canvas,
};
}
// palettize image
const palettized = palettize_1.default(canvas.getContext('2d'), palette);
// return palettized image
return {
canvas: palettized,
palette: palette.getPalette(),
};
};
module.exports = {
draw,
DEFAULT_OPTIONS,
canvas: canvas_1.default,
};
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/draw/index.ts"],"names":[],"mappings":";;;;;A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AAG,EAAE,WAAW,CAAC,CAAC;oBACnD,8BAA8B;oBAC9B,aAAa,GAAG,SAAS,CAAC;iBAC1B;qBAAM;oBACN,UAAU,GAAG,GAAG,CAAC;iBACjB;gBAED,kCAAkC;gBAClC,IAAI,UAAU,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,UAAU,CAAC,EAAE;oBAClD,GAAG,CAAC,SAAS,EAAE,CAAC;oBAChB,GAAG,CAAC,WAAW,GAAG,OAAO,CAAC,aAAa,CAAC,UAAU,CAAC,CAAC;oBACpD,GAAG,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,GAAG,GAAG,QAAQ,CAAC,GAAG,KAAK,EAAE,UAAU,EAAE,QAAQ,CAAC,CAAC;oBAC9D,GAAG,CAAC,MAAM,EAAE,CAAC;iBACb;aACD;SACD;IACF,CAAC,CAAC,CAAC;IAEH,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE;QACxB,gCAAgC;QAC/B,OAAO;YACN,MAAM;SACN,CAAC;KACF;IAED,kBAAkB;IAClB,MAAM,UAAU,GAAG,mBAAc,CAAC,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,OAAO,CAAC,CAAC;IAEpE,0BAA0B;IAC1B,OAAO;QACN,MAAM,EAAE,UAAU;QAClB,OAAO,EAAE,OAAO,CAAC,UAAU,EAAE;KLine truncated
+102
View File
@@ -0,0 +1,102 @@
"use strict";
// ingest a palette and provide lookup and formatting functionality
// {palette: [r1,g1,b1,a1, r2,g2,b2,a2, ...], limits: [1,2, ...]}
// rgba values are returned with the the color index in the g position with 100% opacity
// 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
Object.defineProperty(exports, "__esModule", { value: true });
const rgbaLookupSize = 200;
class Palette {
palette;
limits;
transparentIndex;
lookupRgba;
closest;
downSampleReset;
downSample;
inDeadband;
constructor(palette) {
this.palette = palette.palette;
this.limits = palette.limits;
this.transparentIndex = palette.transparentIndex ?? 0;
this.lookupRgba = findDbzRbgaGenerator(this.limits, this.palette, palette.maxDbzIndex);
this.closest = {};
this.downSampleReset = palette.downSampleReset ?? -Infinity;
if (typeof palette.downSample === 'function') {
this.downSample = palette.downSample;
}
else {
this.downSample = downSample;
}
if (typeof palette.inDeadband === 'function') {
this.inDeadband = palette.inDeadband;
}
else {
this.inDeadband = inDeadband(this.downSampleReset);
}
}
findColorRgba(dbz) {
// find the rgba value of the color from the provided dbz value
return this.lookupRgba[Math.trunc(dbz + rgbaLookupSize)];
}
getPalette() {
// return the palette properly formatted for the PNG function
const dest = new Uint8ClampedArray(256 * 4);
this.palette.forEach((val, idx) => {
dest[idx] = val;
});
return dest;
}
transparentColorRgba() {
// return the rgba value of the transparent color
const index = this.transparentIndex;
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]]
closestIndex(match) {
// short circuit for transparent (black)
if (match[0] <= 2 && match[1] <= 2 && match[2] <= 2)
return this.transparentIndex;
// 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');
if (this.closest[asHex])
return this.closest[asHex];
// initial conditions
let closestIndex = 0;
let closest = Infinity;
// loop through array
for (let i = 0; i < this.palette.length; i += 4) {
const dist = Palette.geometricDistance(match, this.palette.slice(i, i + match.length));
// test for closer
if (dist < closest) {
closest = dist;
closestIndex = i / 4;
if (dist === 0)
break;
}
}
// store closest match to speed up next iteration
this.closest[asHex] = closestIndex;
return closestIndex;
}
// geometric distance
static geometricDistance(a, b) {
return Array.from(a).reduce((acc, val, idx) => acc + (val - b[idx]) ** 2, 0);
}
}
exports.default = Palette;
// create a lookup table of colors for faster processing
const findDbzRbgaGenerator = (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(`rgba(${palette[index * 4]},${palette[index * 4 + 1]},${palette[index * 4 + 2]},${palette[(index * 4 + 3)] / 255})`);
}
return lookupRgba;
};
const downSample = (cur, prev) => (cur === null ? prev : Math.max(cur, prev));
const inDeadband = (reset) => (a) => (a === null || a === reset || a === undefined);
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/draw/palettes/index.ts"],"names":[],"mappings":";AAAA,mEAAmE;AACnE,iEAAiE;AACjE,wFAAwF;AACxF,sGAAsG;AACtG,oFAAoF;;AAIpF,MAAM,cAAc,GAAG,GAAG,CAAC;AAM3B,MAAqB,OAAO;IAC3B,OAAO,CAAW;IAClB,MAAM,CAAW;IACjB,gBAAgB,CAAS;IACzB,UAAU,CAAW;IACrB,OAAO,CAAU;IACjB,eAAe,CAAS;IACxB,UAAU,CAAoC;IAC9C,UAAU,CAA0B;IAEpC,YAAY,OAAmB;QAC9B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;QAC/B,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;QAC7B,IAAI,CAAC,gBAAgB,GAAG,OAAO,CAAC,gBAAgB,IAAI,CAAC,CAAC;QACtD,IAAI,CAAC,UAAU,GAAG,oBAAoB,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,WAAW,CAAC,CAAC;QACvF,IAAI,CAAC,OAAO,GAAG,EAAE,CAAC;QAElB,IAAI,CAAC,eAAe,GAAG,OAAO,CAAC,eAAe,IAAI,CAAC,QAAQ,CAAC;QAC5D,IAAI,OAAO,OAAO,CAAC,UAAU,KAAK,UAAU,EAAE;YAC7C,IAAI,CAAC,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC;SACrC;aAAM;YACN,IAAI,CAAC,UAAU,GAAG,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AAE,EAAE,CAAC,CAAC,CAAQ,EAAE,EAAE,CAAC,CAAC,CAAC,KAAK,IAAI,IAAI,CAAC,KAAK,KAAK,IAAI,CAAC,KAAK,SAAS,CAAC,CAAC"}
+42
View File
@@ -0,0 +1,42 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const palette = [
255, 255, 255, 0,
0, 128, 128, 192,
1, 80, 128, 192,
0, 0, 128, 192,
0, 255, 0, 255,
0, 200, 0, 255,
0, 144, 0, 255,
255, 255, 0, 255,
231, 192, 0, 255,
255, 144, 0, 255,
255, 0, 0, 255,
214, 0, 0, 255,
192, 0, 0, 255,
255, 0, 255, 255,
153, 85, 201, 255,
// additional halfway to black values for cleaner picture
0, 64, 64, 96,
1, 40, 64, 96,
0, 0, 64, 96,
0, 128, 0, 128,
0, 100, 0, 128,
0, 72, 0, 128,
128, 128, 0, 128,
116, 96, 0, 128,
128, 72, 0, 128,
128, 0, 0, 128,
107, 0, 0, 128,
96, 0, 0, 128,
128, 0, 128, 128,
77, 43, 101, 128,
];
const limits = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75];
const paletteData = {
palette,
limits,
maxDbzIndex: 14,
};
exports.default = paletteData;
//# sourceMappingURL=ref.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"ref.js","sourceRoot":"","sources":["../../../src/draw/palettes/ref.ts"],"names":[],"mappings":";;AAEA,MAAM,OAAO,GAAY;IACxB,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC;IAChB,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG;IAChB,CAAC,EAAE,EAAE,EAAE,GAAG,EAAE,GAAG;IACf,CAAC,EAAE,CAAC,EAAE,GAAG,EAAE,GAAG;IACd,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,GAAG;IACd,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,GAAG;IACd,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,GAAG;IAC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AE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC;AAErF,MAAM,WAAW,GAAgB;IAChC,OAAO;IACP,MAAM;IACN,WAAW,EAAE,EAAE;CACf,CAAC;AAEF,kBAAe,WAAW,CAAC"}
+56
View File
@@ -0,0 +1,56 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const palette = [
// 0: green/outbound
0, 255, 0, 255,
0, 240, 0, 255,
0, 223, 0, 255,
0, 206, 0, 255,
0, 189, 0, 255,
0, 172, 0, 255,
0, 155, 0, 255,
0, 138, 0, 255,
16, 121, 16, 255,
32, 113, 32, 255,
48, 104, 48, 255,
// 11: nearly zero
64, 95, 64, 255,
95, 64, 64, 255,
// 13: red/inbound
104, 32, 32, 255,
113, 16, 16, 255,
121, 0, 0, 255,
138, 0, 0, 255,
155, 0, 0, 255,
172, 0, 0, 255,
189, 0, 0, 255,
206, 0, 0, 255,
223, 0, 0, 255,
240, 0, 0, 255,
255, 0, 0, 255,
// 24: transparent
255, 255, 255, 0,
];
const downSample = (cur, prev) => {
// no data, use previous value
if (cur === null)
return prev;
// test for magnitude change, prev may be null but Math.abs(null) === 0 so this is valid
if (Math.abs(cur) >= Math.abs(prev))
return cur;
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 downSampleReset = null;
const transparentIndex = 24;
const paletteData = {
palette,
downSample,
limits,
downSampleReset,
transparentIndex,
maxDbzIndex: 23,
};
exports.default = paletteData;
//# sourceMappingURL=vel.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"vel.js","sourceRoot":"","sources":["../../../src/draw/palettes/vel.ts"],"names":[],"mappings":";;AAEA,MAAM,OAAO,GAAY;IACxB,oBAAoB;IACpB,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,GAAG;IACd,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,GAAG;IACd,CAAC,E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IAAI;QAAE,OAAO,IAAI,CAAC;IAC9B,wFAAwF;IACxF,IAAI,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC;QAAE,OAAO,GAAG,CAAC;IAChD,OAAO,IAAI,CAAC;AACb,CAAC,CAAC;AAEF,MAAM,MAAM,GAAa,CAAC,CAAC,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE;CACpI,CAAC;AAEF,MAAM,eAAe,GAAG,IAAI,CAAC;AAE7B,MAAM,gBAAgB,GAAG,EAAE,CAAC;AAE5B,MAAM,WAAW,GAAgB;IAChC,OAAO;IACP,UAAU;IACV,MAAM;IACN,eAAe;IACf,gBAAgB;IAChB,WAAW,EAAE,EAAE;CACf,CAAC;AAEF,kBAAe,WAAW,CAAC"}
+30
View File
@@ -0,0 +1,30 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const canvas_1 = require("canvas");
const palettizeImage = (sourceCtx, palette) => {
// get the dimensions of the image from the ctx
const dim = {
x: sourceCtx.canvas.width,
y: sourceCtx.canvas.height,
};
console.time('Palettize image');
// transform into indexed palette by finding the closest indexed color for each pixel
// create a destination image that is transparent and indexed
const indexedCanvas = canvas_1.createCanvas(dim.x, dim.y);
const indexedCtx = indexedCanvas.getContext('2d', { pixelFormat: 'A8' });
// get the source image data
const sourceImageData = sourceCtx.getImageData(0, 0, dim.x, dim.y);
// get the indexed image data (destination)
const indexedImageData = indexedCtx.getImageData(0, 0, dim.x, dim.y);
// loop through each pixel
console.log(`Palettized cache size: ${Object.keys(palette.closest).length}`);
indexedImageData.data.forEach((val, idx) => {
indexedImageData.data[idx] = palette.closestIndex(sourceImageData.data.slice(idx * 4, idx * 4 + 3));
});
console.timeEnd('Palettize image');
// write the new image data
indexedCtx.putImageData(indexedImageData, 0, 0);
return indexedCanvas;
};
exports.default = palettizeImage;
//# sourceMappingURL=palettize.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"palettize.js","sourceRoot":"","sources":["../../src/draw/palettize.ts"],"names":[],"mappings":";;AAAA,mCAAwE;AAGxE,MAAM,cAAc,GAAG,CAAC,SAAkC,EAAE,OAAgB,EAAS,EAAE;IACtF,+CAA+C;IAC/C,MAAM,GAAG,GAAG;QACX,CAAC,EAAE,SAAS,CAAC,MAAM,CAAC,KAAK;QACzB,CAAC,EAAE,SAAS,CAAC,MAAM,CAAC,MAAM;KAC1B,CAAC;IACF,OAAO,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAC;IAEhC,qFAAqF;IACrF,6DAA6D;IAC7D,MAAM,aAAa,GAAG,qBAAY,CAAC,GAAG,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC;IACjD,MAAM,UAAU,GAAG,aAAa,CAAC,UAAU,CAAC,IAAI,EAAE,EAAE,WAAW,EAAE,IAAI,EAAE,CAAC,CAAC;IAEzE,4BAA4B;IAC5B,MAAM,eAAe,GAAG,SAAS,CAAC,YAAY,CAAC,CAAC,EAAE,CAAC,EAAE,GAAG,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC;IACnE,2CAA2C;IAC3C,MAAM,gBAAgB,GAAG,UAAU,CAAC,YAAY,CAAC,CAAC,EAAE,CAAC,EAAE,GAAG,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC;IAErE,0BAA0B;IAC1B,OAAO,CAAC,GAAG,CAAC,0BAA0B,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC;IAC7E,gBAAgB,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,EAAE;QAC1C,gBAAgB,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,YAAY,CAAC,eAAe,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,GAAG,CAAC,EAAE,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;IACrG,CAAC,CAAC,CAAC;IACH,OAAO,CAAC,OAAO,CAAC,iBAAiB,CAAC,CAAC;IACnC,2BAA2B;IAC3B,UAAU,CAAC,YAAY,CAAC,gBAAgB,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAEhD,OAAO,aAAa,CAAC;AACtB,CAAC,CAAC;AAEF,kBAAe,cAAc,CAAC"}
+49
View File
@@ -0,0 +1,49 @@
"use strict";
const { draw, canvas } = require('./draw');
const { writePngToFile } = require('./utils/file');
/**
* Plot level 2 data
* @param {Level2Data} data output from the nexrad-level-2-data library
* @param {(string|string[])} _products Options are REF, VEL, SW , ZDR, PHI and RHO
* @param {object} options Plotting options
* @param {number} [options.size=3600] 1 to 3600. Size of the x and y axis in pixels. The image must be square so only a single integer is needed.
* @param {number} [options.cropTo=3600] 1 to 3600. After scaling and downsampling as described above crop the resulting plot to the size specified. Internally, the image is actually drawn at the cropped size to save on processing time.
* @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 {(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.
* @returns Canvas
*/
const plot = (data, _products, options) => {
// store result
const result = {};
let products;
// make product list into an array
if (_products && Array.isArray(_products)) {
products = _products;
}
else if (typeof _products === 'string') {
products = [_products];
}
else {
// default to all products
products = ['REF', 'VEL', 'SW ', 'ZDR', 'PHI', 'RHO'];
}
// get the available elevations
const elevations = data.listElevations();
if (elevations.length === 0)
throw new Error('No elevations availabe');
products.forEach((product) => {
// parse and store result
result[product] = draw(data, {
...options,
product,
});
});
return result;
};
module.exports = {
plot,
writePngToFile,
canvas,
};
//# sourceMappingURL=index.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.js"],"names":[],"mappings":";AAAA,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;AAC3C,MAAM,EAAE,cAAc,EAAE,GAAG,OAAO,CAAC,cAAc,CAAC,CAAC;AACnD;;;;;;;;;;;GAWG;AACH,MAAM,IAAI,GAAG,CAAC,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,EAAE;IACzC,eAAe;IACf,MAAM,MAAM,GAAG,EAAE,CAAC;IAElB,IAAI,QAAQ,CAAC;IACb,kCAAkC;IAClC,IAAI,SAAS,IAAI,KAAK,CAAC,OAAO,CAAC,SAAS,CAAC,EAAE;QAC1C,QAAQ,GAAG,SAAS,CAAC;KACrB;SAAM,IAAI,OAAO,SAAS,KAAK,QAAQ,EAAE;QACzC,QAAQ,GAAG,CAAC,SAAS,CAAC,CAAC;KACvB;SAAM;QACN,0BAA0B;QAC1B,QAAQ,GAAG,CAAC,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC;KACtD;IAED,+BAA+B;IAC/B,MAAM,UAAU,GAAG,IAAI,CAAC,cAAc,EAAE,CAAC;IACzC,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAC;IAEvE,QAAQ,CAAC,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;QAC5B,yBAAyB;QACzB,MAAM,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC,IAAI,EAAE;YAC5B,GAAG,OAAO;YACV,OAAO;SACP,CAAC,CAAC;IACJ,CAAC,CAAC,CAAC;IACH,OAAO,MAAM,CAAC;AACf,CAAC,CAAC;AAEF,MAAM,CAAC,OAAO,GAAG;IAChB,IAAI;IACJ,cAAc;IACd,MAAM;CACN,CAAC"}
+3
View File
@@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=types.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}
+31
View File
@@ -0,0 +1,31 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const fs = require('fs');
// write a canvas to a Png file
/**
* Write a Canvas to the specified file
* @param {string} fileName Path to write output to, passed to fs.createWriteStream
* @param {Canvas} data Canvas provided by the plot() function
* @returns Promise
*/
const writePngToFile = (fileName, data) => new Promise((resolve, reject) => {
// the draw function will return false if no data was found, short circuit the output here
if (!data.canvas) {
resolve();
return;
}
// get a write stream
const writeStream = fs.createWriteStream(fileName);
// options
const options = {};
if (data.palette)
options.palette = data.palette;
// write to the stream
data.canvas.createPNGStream(options).pipe(writeStream);
writeStream.on('finish', () => resolve());
writeStream.on('error', (e) => reject(e));
});
module.exports = {
writePngToFile,
};
//# sourceMappingURL=file.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"file.js","sourceRoot":"","sources":["../../src/utils/file.ts"],"names":[],"mappings":";;AAGA,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;AACzB,+BAA+B;AAC/B;;;;;GAKG;AACH,MAAM,cAAc,GAAG,CAAC,QAAgB,EAAE,IAAU,EAAE,EAAE,CAAC,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;IAC9F,0FAA0F;IAC1F,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE;QACjB,OAAO,EAAE,CAAC;QACV,OAAO;KACP;IAED,qBAAqB;IACrB,MAAM,WAAW,GAAG,EAAE,CAAC,iBAAiB,CAAC,QAAQ,CAAC,CAAC;IAEnD,UAAU;IACV,MAAM,OAAO,GAAa,EAAE,CAAC;IAC7B,IAAI,IAAI,CAAC,OAAO;QAAE,OAAO,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;IAEjD,sBAAsB;IACtB,IAAI,CAAC,MAAM,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;IACvD,WAAW,CAAC,EAAE,CAAC,QAAQ,EAAE,GAAG,EAAE,CAAC,OAAO,EAAE,CAAC,CAAC;IAC1C,WAAW,CAAC,EAAE,CAAC,OAAO,EAAE,CAAC,CAAQ,EAAE,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;AAClD,CAAC,CAAC,CAAC;AAEH,MAAM,CAAC,OAAO,GAAG;IAChB,cAAc;CACd,CAAC"}
-8
View File
@@ -1,8 +0,0 @@
{
"folders": [
{
"path": "."
}
],
"settings": {}
}
+3 -3
View File
@@ -1,4 +1,4 @@
# Ignore everything in this directory as it is generated dynamically
*
# Except this file
# Ignore everything in this directory as it is generated dynamically
*
# Except this file
!.gitignore
+5421 -3897
View File
File diff suppressed because it is too large. Load diff
+42 -37
View File
@@ -1,39 +1,44 @@
{
"name": "nexrad-level-2-plot",
"version": "2.5.0",
"description": "Plotting library for nexrad-level-2-data",
"main": "src/index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/netbymatt/nexrad-level-2-plot.git"
},
"keywords": [
"NEXRAD",
"level",
"2",
"radar",
"plot"
],
"author": "Matt Walsh",
"license": "MIT",
"bugs": {
"url": "https://github.com/netbymatt/nexrad-level-2-plot/issues"
},
"homepage": "https://github.com/netbymatt/nexrad-level-2-plot#readme",
"dependencies": {
"canvas": "^2.9.1",
"nexrad-level-2-data": "^2.3.5"
},
"devDependencies": {
"eslint": "^8.0.0",
"eslint-config-airbnb-base": "^15.0.0",
"eslint-plugin-import": "^2.23.4",
"glob": "^7.1.7"
},
"engines": {
"node": ">=13.0.0"
}
"name": "nexrad-level-2-plot",
"version": "1.0.0",
"description": "Plotting library for nexrad-level-2-data",
"main": "src/index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/netbymatt/nexrad-level-2-plot.git"
},
"keywords": [
"NEXRAD",
"level",
"2",
"radar",
"plot"
],
"author": "Matt Walsh",
"license": "MIT",
"bugs": {
"url": "https://github.com/netbymatt/nexrad-level-2-plot/issues"
},
"homepage": "https://github.com/netbymatt/nexrad-level-2-plot#readme",
"dependencies": {
"canvas": "^2.8.0",
"nexrad-level-2-data": "file:../nexrad-level-2-data"
},
"devDependencies": {
"@types/node": "^16.7.2",
"@typescript-eslint/eslint-plugin": "^4.29.3",
"@typescript-eslint/parser": "^4.29.3",
"eslint": "^7.32.0",
"eslint-config-airbnb-base": "^14.2.1",
"eslint-import-resolver-typescript": "^2.4.0",
"eslint-plugin-import": "^2.23.4",
"glob": "^7.1.7",
"typescript": "^4.3.5"
},
"engines": {
"node": ">=13.0.0"
}
}
+18 -16
View File
@@ -3,7 +3,7 @@ const { Level2Radar } = require('nexrad-level-2-data');
const glob = require('glob');
const fs = require('fs');
const { plot, writePngToFile } = require('../src');
const { plot, writePngToFile } = require('../index');
// list files
// const files = glob.sync('./data/KLOT/34/*');
@@ -27,10 +27,13 @@ files.forEach((file) => {
// combine data
const radarData = Level2Radar.combineData(chunks);
// result array by elevations
const plots = [];
// default to all plots unless single is specificed
const single = process.argv.includes('single');
let sizes = [1800];
let sizes = [3600, 1800, 900, 800, 600, 450, 100];
let elevations = radarData.listElevations();
if (single) {
sizes = sizes.slice(0, 1);
@@ -43,20 +46,19 @@ if (single) {
// plot for each elevation and size
(async () => {
await Promise.allSettled(sizes.map(async (size) => {
const plots = plot(radarData, ['REF', 'VEL'], {
elevations,
size,
palettize: true,
cropTo: size / 2,
});
await Promise.allSettled(elevations.map(async (elevation) => {
plots[elevation] = plot(radarData, ['REF', 'VEL'], {
elevation,
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);
// write files to disk
await Promise.allSettled([
writePngToFile(`./output/REF-${elevation}-${size}.png`, plots[elevation].REF),
writePngToFile(`./output/VEL-${elevation}-${size}.png`, plots[elevation].VEL),
]);
}));
}));
})();
-187
View File
@@ -1,187 +0,0 @@
const canvasObj = require('canvas');
const { createCanvas } = canvasObj;
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
const dataNames = {
REF: 'reflect',
VEL: 'velocity',
'SW ': 'spectrum', // intentional space to fill 3-character requirement
ZDR: 'zdr',
PHI: 'phi',
RHO: 'rho',
};
// names of data retrieval routines keyed to product name
const dataFunctions = {
REF: 'getHighresReflectivity',
VEL: 'getHighresVelocity',
};
// generate all palettes
/* eslint-disable global-require */
const palettes = {
REF: new Palette(require('./palettes/ref')),
VEL: new Palette(require('./palettes/vel')),
};
/* 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
const DEFAULT_OPTIONS = {
// must be a square image
size: 3600,
cropTo: 3600,
background: 'black',
lineWidth: 2,
usePreferredWaveforms: true,
};
const draw = (data, _options) => {
// combine options with defaults
const options = {
...DEFAULT_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
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');
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
console.log('');
console.log(`ELEVATION: ${options.product} ${options.elevation}`);
console.log(`Gate size: ${data?.data?.[options.elevation]?.[0]?.record?.reflect?.gate_size}`);
console.log('Super Res:', data?.vcp?.record?.elevations?.[options.elevation]?.super_res_control?.super_res);
console.log(`Gate count: ${data?.data?.[options.elevation]?.[0]?.record?.reflect.gate_count}`);
const cropTo = Math.min(options.size, options.cropTo);
if (options.cropTo < 1) throw new Error('Provide options.cropTo > 0');
// create the canvas and context
const canvas = createCanvas(cropTo, cropTo);
const ctx = canvas.getContext('2d');
// 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
const palette = palettes[options.product];
// test for valid palette
if (!palette) throw new Error(`No product found for product type: ${options.product}`);
// set the elevation
data.setElevation(options.elevation);
// get the header data
const headers = data.getHeader();
// calculate resolution in radians, default to 1°
let resolution = Math.PI / 180;
if (data?.vcp?.record?.elevations?.[options.elevation]?.super_res_control?.super_res?.halfDegreeAzimuth) resolution /= 2;
// calculate half resolution step for additional calculations below
const halfResolution = resolution / 2;
// match product name to data
const dataName = dataNames[options.product];
const dataFunction = dataFunctions[options.product];
// check for valid product
if (dataName === undefined) throw new Error(`No data object name found for product: ${options.product}`);
if (dataFunction === undefined) throw new Error(`No data function found for product: ${options.product}`);
// check for data for this product
if (headers[0][dataName] === undefined) return false;
// 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
rrlEncoded.forEach((radial) => {
// calculate plotting parameters
const deadZone = radial.first_gate / radial.gate_size / scale;
// 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 startAngle = radial.azimuth * (Math.PI / 180) - halfResolution * 1.1;
const endAngle = radial.azimuth * (Math.PI / 180) + halfResolution * 1.1;
// plot each bin
radial.moment_data.forEach((bin, idx) => {
if (bin !== null) {
ctx.beginPath();
// different methods for rrle encoded or not
if (bin.count) {
// rrle encoded
ctx.strokeStyle = palette.lookupRgba[bin.value];
ctx.arc(0, 0, (idx + deadZone) * gateSizeScaling, startAngle, endAngle + resolution * (bin.count - 1));
} else {
// plain data
ctx.strokeStyle = palette.lookupRgba[bin];
ctx.arc(0, 0, (idx + deadZone) * gateSizeScaling, startAngle, endAngle);
}
ctx.stroke();
}
});
});
if (!options.palettize) {
// return the palette and canvas
return {
canvas,
};
}
// palettize image
const palettized = palettizeImage(canvas.getContext('2d'), palette);
// return palettized image
return {
canvas: palettized,
palette: palette.getPalette(),
};
};
module.exports = {
draw,
DEFAULT_OPTIONS,
canvas: canvasObj,
};
+195
View File
@@ -0,0 +1,195 @@
import canvasObj from 'canvas';
import Palette from './palettes';
import REF from './palettes/ref';
import VEL from './palettes/vel';
import palettizeImage from './palettize';
import { DrawOptions } from '../types';
const { createCanvas } = canvasObj;
interface ObjectStrings {
[key: string]: string,
}
// names of data structures keyed to product name
const dataNames:ObjectStrings = {
REF: 'reflect',
VEL: 'velocity',
'SW ': 'spectrum', // intentional space to fill 3-character requirement
ZDR: 'zdr',
PHI: 'phi',
RHO: 'rho',
};
// names of data retrieval routines keyed to product name
const dataFunctions:ObjectStrings = {
REF: 'getHighresReflectivity',
VEL: 'getHighresVelocity',
};
interface Palettes {
[key: string]: Palette,
}
// generate all palettes
const palettes:Palettes = {
REF: new Palette(REF),
VEL: new Palette(VEL),
};
// default options
export const DEFAULT_OPTIONS = {
// must be a square image
size: 3600,
cropTo: 3600,
background: 'black',
lineWidth: 2,
};
// calculation constants
const RAD45 = ((45 * Math.PI) / 180);
const RAD90 = RAD45 * 2;
export interface draw {
canvas: canvasObj.Canvas,
palette?: Uint8ClampedArray,
}
export const draw = (data, _options:DrawOptions):draw => {
// combine options with defaults
const options = {
...DEFAULT_OPTIONS,
..._options,
};
// calculate scale
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');
const scale = DEFAULT_OPTIONS.size / options.size;
// calculate crop, adjust if necessary
const cropTo = Math.min(options.size, options.cropTo);
if (options.cropTo < 1) throw new Error('Provide options.cropTo > 0');
// create the canvas and context
const canvas = createCanvas(cropTo, cropTo);
const ctx = canvas.getContext('2d');
// fill background with black
ctx.fillStyle = options.background;
ctx.fillRect(0, 0, cropTo, cropTo);
// canvas settings
ctx.imageSmoothingEnabled = true;
ctx.lineWidth = options.lineWidth;
ctx.translate(cropTo / 2, cropTo / 2);
ctx.rotate(-Math.PI / 2);
// get the palette
const palette = palettes[options.product];
// test for valid palette
if (!palette) throw new Error(`No product found for product type: ${options.product}`);
// set the elevation
data.setElevation(options.elevation);
// get the header data
const headers = data.getHeader();
// calculate resolution in radians, default to 1°
let resolution = Math.PI / 180;
if (data?.vcp?.record?.elevation?.s[options.elevation]?.super_res_control?.super_res?.halfDegreeAzimuth) resolution /= 2;
// calculate half resolution step for additional calculations below
const halfResolution = resolution / 2;
// match product name to data
const dataName = dataNames[options.product];
const dataFunction = dataFunctions[options.product];
// check for valid product
if (dataName === undefined) throw new Error(`No data object name found for product: ${options.product}`);
if (dataFunction === undefined) throw new Error(`No data function found for product: ${options.product}`);
// check for data for this product
if (headers[0][dataName] === undefined) throw new Error('No data for this product');
// loop through data
headers.forEach((header) => {
// get correct data
const thisRadial = header[dataName];
// skip if this radial isn't found
if (thisRadial === undefined) return;
// calculate plotting parameters
const deadZone = thisRadial.first_gate / thisRadial.gate_size;
const startAngle = header.azimuth * (Math.PI / 180) - halfResolution;
const endAngle = startAngle + resolution;
// 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
for (let idx = 0; idx < maxBin; idx += 1) {
// get the value
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
downsampled = palette.downSample(bin, downsampled);
// store for rollover tracking
lastRemainder = remainder;
} else {
thisSample = bin;
}
// see if there's a sample to plot
if (thisSample && !palette.inDeadband(thisSample)) {
ctx.beginPath();
ctx.strokeStyle = palette.findColorRgba(thisSample);
ctx.arc(0, 0, (idx + deadZone) / scale, startAngle, endAngle);
ctx.stroke();
}
}
}
});
if (!options.palettize) {
// return the palette and canvas
return {
canvas,
};
}
// palettize image
const palettized = palettizeImage(canvas.getContext('2d'), palette);
// return palettized image
return {
canvas: palettized,
palette: palette.getPalette(),
};
};
export { Canvas } from 'canvas';
@@ -4,23 +4,32 @@
// 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
import { PaletteData } from '../../types';
const rgbaLookupSize = 200;
class Palette {
constructor(palette) {
interface Closest {
[key: string]: number,
}
export default class Palette {
palette: number[];
limits: number[];
transparentIndex: number;
lookupRgba: string[];
closest: Closest;
downSampleReset: number;
downSample: (cur:number, prev:number)=>number;
inDeadband: (reset:number)=>boolean;
constructor(palette:PaletteData) {
this.palette = palette.palette;
this.limits = palette.limits;
this.transparentIndex = palette.transparentIndex;
this.transparentIndex = palette.transparentIndex ?? 0;
this.lookupRgba = findDbzRbgaGenerator(this.limits, this.palette, palette.maxDbzIndex);
this.lookupIndex = findDbzIndexGenerator(this.limits, this.palette, palette.maxDbzIndex);
this.closest = {};
// these may not exist and are overridden with default functions
if (palette.hasOwnProperty('downSampleReset')) {
this.downSampleReset = palette.downSampleReset;
} else {
this.downSampleReset = -Infinity;
}
this.downSampleReset = palette.downSampleReset ?? -Infinity;
if (typeof palette.downSample === 'function') {
this.downSample = palette.downSample;
} else {
@@ -34,12 +43,12 @@ class Palette {
}
}
findColorIndex(dbz) {
findColorRgba(dbz:number):string {
// find the rgba value of the color from the provided dbz value
return this.lookupIndex[Math.trunc(dbz + rgbaLookupSize)];
return this.lookupRgba[Math.trunc(dbz + rgbaLookupSize)];
}
getPalette() {
getPalette():Uint8ClampedArray {
// return the palette properly formatted for the PNG function
const dest = new Uint8ClampedArray(256 * 4);
this.palette.forEach((val, idx) => {
@@ -48,14 +57,14 @@ class Palette {
return dest;
}
transparentColorRgba() {
transparentColorRgba():string {
// return the rgba value of the transparent color
const index = this.transparentIndex;
const index:number = this.transparentIndex;
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]]
closestIndex(match) {
closestIndex(match:ArrayLike<number>):number {
// short circuit for transparent (black)
if (match[0] <= 2 && match[1] <= 2 && match[2] <= 2) return this.transparentIndex;
// short circuit previously calculated matches
@@ -80,34 +89,23 @@ class Palette {
}
// geometric distance
static geometricDistance(a, b) {
return a.reduce((acc, val, idx) => acc + (val - b[idx]) ** 2, 0);
static geometricDistance(a:ArrayLike<number>, b:ArrayLike<number>):number {
return Array.from(a).reduce((acc:number, val:number, idx:number) => acc + (val - b[idx]) ** 2, 0);
}
}
// 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) => {
// create a lookup table of colors for faster processing
const findDbzRbgaGenerator = (limits:number[], palette:number[], maxDbzIndex = 14):string[] => {
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);
lookupRgba.push(`rgba(${palette[index * 4]},${palette[index * 4 + 1]},${palette[index * 4 + 2]},${palette[(index * 4 + 3)] / 255})`);
}
return lookupRgba;
};
const downSample = (cur, prev) => (cur === null ? prev : Math.max(cur, prev));
const downSample = (cur:number, prev:number):number => (cur === null ? prev : Math.max(cur, prev));
const inDeadband = (reset) => (a) => (a === null || a === reset || a === undefined);
module.exports = Palette;
const inDeadband = (reset:number) => (a:number) => (a === null || a === reset || a === undefined);
@@ -1,4 +1,6 @@
const palette = [
import { PaletteData } from '../../types';
const palette:number[] = [
255, 255, 255, 0, // transparent
0, 128, 128, 192,
1, 80, 128, 192,
@@ -32,15 +34,12 @@ const palette = [
77, 43, 101, 128,
];
const maxDbzIndex = 14; // index of maximum dbz
const limits:number[] = [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;
module.exports = {
const paletteData: PaletteData = {
palette,
maxDbzIndex,
limits,
transparentIndex,
maxDbzIndex: 14,
};
export default paletteData;
@@ -1,4 +1,6 @@
const palette = [
import { PaletteData } from '../../types';
const palette:number[] = [
// 0: green/outbound
0, 255, 0, 255,
0, 240, 0, 255,
@@ -33,7 +35,7 @@ const palette = [
255, 255, 255, 0,
];
const downSample = (cur, prev) => {
const downSample = (cur:number, prev:number): number => {
// no data, use previous value
if (cur === null) return prev;
// test for magnitude change, prev may be null but Math.abs(null) === 0 so this is valid
@@ -41,20 +43,20 @@ const downSample = (cur, 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:number[] = [-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 maxDbzIndex = 12; // index of maximum dbz
const transparentIndex = 24;
module.exports = {
const paletteData: PaletteData = {
palette,
downSample,
limits,
downSampleReset,
maxDbzIndex,
transparentIndex,
maxDbzIndex: 23,
};
export default paletteData;
@@ -1,11 +1,13 @@
const { createCanvas } = require('canvas');
import { createCanvas, CanvasRenderingContext2D, Canvas } from 'canvas';
import Palette from './palettes';
const palettizeImage = (sourceCtx, palette) => {
const palettizeImage = (sourceCtx:CanvasRenderingContext2D, palette: Palette):Canvas => {
// get the dimensions of the image from the ctx
const dim = {
x: sourceCtx.canvas.width,
y: sourceCtx.canvas.height,
};
console.time('Palettize image');
// transform into indexed palette by finding the closest indexed color for each pixel
// create a destination image that is transparent and indexed
@@ -18,14 +20,15 @@ const palettizeImage = (sourceCtx, palette) => {
const indexedImageData = indexedCtx.getImageData(0, 0, dim.x, dim.y);
// loop through each pixel
console.log(`Palettized cache size: ${Object.keys(palette.closest).length}`);
indexedImageData.data.forEach((val, idx) => {
indexedImageData.data[idx] = palette.closestIndex(sourceImageData.data.slice(idx * 4, idx * 4 + 3));
});
console.timeEnd('Palettize image');
// write the new image data
indexedCtx.putImageData(indexedImageData, 0, 0);
return indexedCanvas;
};
module.exports = palettizeImage;
export default palettizeImage;
-56
View File
@@ -1,56 +0,0 @@
// 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
@@ -1,16 +0,0 @@
// 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
@@ -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;
-77
View File
@@ -1,77 +0,0 @@
// 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];
// check for null
if (target === null) return false;
// 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 (nextI < radials.length && checkNext) {
// 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) => {
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) {
radial.moment_data[binIdx] = { value: bin, count: totalMatches };
for (let clearI = i + 1; clearI <= i + totalMatches - 1; clearI += 1) {
sorted[clearI].moment_data[binIdx] = null;
}
}
});
}
return radials;
};
module.exports = rrle;
+18 -25
View File
@@ -1,5 +1,11 @@
const { draw, canvas } = require('./draw');
const { writePngToFile } = require('./utils/file');
import { draw, Canvas } from './draw';
import { writePngToFile } from './utils/file';
import { DrawOptions } from './types';
interface Results {
[key: string]: draw,
}
/**
* Plot level 2 data
* @param {Level2Data} data output from the nexrad-level-2-data library
@@ -10,13 +16,11 @@ const { writePngToFile } = require('./utils/file');
* @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 {(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.
* @returns Canvas
*/
const plot = (data, _products, options) => {
const plot = (data, _products:string|string[], options:DrawOptions) => {
// store result
const result = [];
const result:Results = {};
let products;
// make product list into an array
@@ -30,32 +34,21 @@ const plot = (data, _products, options) => {
}
// get the available elevations
const availableElevations = data.listElevations();
if (availableElevations.length === 0) throw new Error('No elevations availabe');
const elevations = data.listElevations();
if (elevations.length === 0) throw new Error('No elevations availabe');
// handle options.elevations defaults
let elevations = options?.elevations;
if (!elevations) elevations = availableElevations;
if (typeof elevations === 'number') elevations = [elevations];
elevations.forEach((elevation) => {
const elevationResult = { elevation };
products.forEach((product) => {
// parse and store result
elevationResult[product] = draw(data, {
...options,
elevation,
product,
});
products.forEach((product) => {
// parse and store result
result[product] = draw(data, {
...options,
product,
});
result.push(elevationResult);
});
return result;
};
module.exports = {
plot,
writePngToFile,
canvas,
Canvas,
};
+26
View File
@@ -0,0 +1,26 @@
import { Canvas } from 'canvas';
export interface Plot {
canvas: Canvas,
palette?: Uint8ClampedArray,
}
export interface PaletteData {
palette: number[],
limits: number[],
transparentIndex?: number,
downSampleReset?: number|null,
downSample?: (cur:number, prev:number) => number,
inDeadband?: () => boolean,
maxDbzIndex: number;
}
export interface DrawOptions {
size: number,
cropTo: number,
background: string,
lineWidth: number,
product: string,
elevation: number,
palettize?: boolean,
}
+9 -9
View File
@@ -1,4 +1,7 @@
const fs = require('fs');
import { PngConfig } from 'canvas';
import fs from 'fs';
import { Plot } from '../types';
// write a canvas to a Png file
/**
* Write a Canvas to the specified file
@@ -6,7 +9,8 @@ const fs = require('fs');
* @param {Canvas} data Canvas provided by the plot() function
* @returns Promise
*/
const writePngToFile = (fileName, data) => new Promise((resolve, reject) => {
// eslint-disable-next-line import/prefer-default-export
export const writePngToFile = (fileName: string, data: Plot):Promise<void> => new Promise<void>((resolve, reject) => {
// the draw function will return false if no data was found, short circuit the output here
if (!data.canvas) {
resolve();
@@ -17,15 +21,11 @@ const writePngToFile = (fileName, data) => new Promise((resolve, reject) => {
const writeStream = fs.createWriteStream(fileName);
// options
const options = {};
const options:PngConfig = {};
if (data.palette) options.palette = data.palette;
// write to the stream
data.canvas.createPNGStream(options).pipe(writeStream);
writeStream.on('finish', () => resolve(fileName));
writeStream.on('error', (e) => reject(e));
writeStream.on('finish', () => resolve());
writeStream.on('error', (e: Error) => reject(e));
});
module.exports = {
writePngToFile,
};
+15
View File
@@ -0,0 +1,15 @@
{
"compilerOptions": {
"target": "esnext",
"module": "commonjs",
"allowJs": true,
"checkJs": false,
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"sourceMap": true,
"noImplicitAny": true
}
}