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 | |
|---|---|---|---|
|
|
4246240ee4 |
No files matched your search
Vendored
-9
@@ -12,15 +12,6 @@
|
||||
"<node_internals>/**"
|
||||
],
|
||||
"program": "${workspaceFolder}/demos/test.js"
|
||||
},
|
||||
{
|
||||
"type": "pwa-node",
|
||||
"request": "launch",
|
||||
"name": "Benchmark",
|
||||
"skipFiles": [
|
||||
"<node_internals>/**"
|
||||
],
|
||||
"program": "${workspaceFolder}/demos/benchmark.js"
|
||||
}
|
||||
]
|
||||
}
|
||||
Vendored
+2
-4
@@ -7,13 +7,11 @@
|
||||
"KLOT",
|
||||
"Mult",
|
||||
"NOAA",
|
||||
"Palettized",
|
||||
"RGBA",
|
||||
"palettization",
|
||||
"palettize",
|
||||
"Palettized",
|
||||
"palletizing",
|
||||
"Rbga",
|
||||
"RGBA",
|
||||
"rrle",
|
||||
"uncommenting"
|
||||
]
|
||||
}
|
||||
@@ -79,7 +79,9 @@ A full size plot is 3600 x 3600 pixels. This corresponds to the maximum range of
|
||||
|
||||
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.
|
||||
@@ -88,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.
|
||||
|
||||
@@ -106,13 +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
|
||||
|
||||
## v1.1.0 Notable, RRLE pre-processing
|
||||
Testing and monitoring of this package in production showed that drawing each 0.5° or 1.0° 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/)
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
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);
|
||||
|
||||
// result array by elevations
|
||||
const plots = [];
|
||||
|
||||
const size = 1800;
|
||||
const elevation = 1;
|
||||
|
||||
// plot for each elevation and size
|
||||
(async () => {
|
||||
const start = new Date();
|
||||
for (let i = 0; i < 100; i += 1) {
|
||||
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}--${i}.png`, plots[elevation].REF),
|
||||
writePngToFile(`./output/VEL-${elevation}-${size}--${i}.png`, plots[elevation].VEL),
|
||||
]);
|
||||
}
|
||||
const end = new Date();
|
||||
console.log(`Total Time: ${(end - start) / 1000}`);
|
||||
})();
|
||||
+7
-7
@@ -3,16 +3,16 @@ const { Level2Radar } = require('nexrad-level-2-data');
|
||||
const glob = require('glob');
|
||||
const fs = require('fs');
|
||||
|
||||
const { plot, writePngToFile } = require('../src');
|
||||
const { plot, writeSvgToFile } = require('../src');
|
||||
|
||||
// list files
|
||||
// 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/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/KLOT20210812_171451_V*'); // ref palette tuning
|
||||
// const files = glob.sync('./data/KLOT/KLOT20210621_041151_V06'); // vel palette tuning
|
||||
|
||||
// const store each file's data
|
||||
@@ -33,7 +33,7 @@ const plots = [];
|
||||
// default to all plots unless single is specificed
|
||||
const single = process.argv.includes('single');
|
||||
|
||||
let sizes = [1800];
|
||||
let sizes = [900, 450, 100];
|
||||
let elevations = radarData.listElevations();
|
||||
if (single) {
|
||||
sizes = sizes.slice(0, 1);
|
||||
@@ -51,13 +51,13 @@ if (single) {
|
||||
elevation,
|
||||
size,
|
||||
palettize: true,
|
||||
cropTo: size / 2,
|
||||
// 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),
|
||||
writeSvgToFile(`./output/REF-${elevation}-${size}.svg`, plots[elevation].REF),
|
||||
writeSvgToFile(`./output/VEL-${elevation}-${size}.svg`, plots[elevation].VEL),
|
||||
]);
|
||||
}));
|
||||
}));
|
||||
|
||||
+3
-3
@@ -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
|
||||
Generated
+2360
-1020
File diff suppressed because it is too large.
Load diff
+6
-5
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "nexrad-level-2-plot",
|
||||
"version": "1.1.2",
|
||||
"version": "1.0.0",
|
||||
"description": "Plotting library for nexrad-level-2-data",
|
||||
"main": "src/index.js",
|
||||
"scripts": {
|
||||
@@ -24,12 +24,13 @@
|
||||
},
|
||||
"homepage": "https://github.com/netbymatt/nexrad-level-2-plot#readme",
|
||||
"dependencies": {
|
||||
"canvas": "^2.8.0",
|
||||
"nexrad-level-2-data": "^2.1.0"
|
||||
"@svgdotjs/svg.js": "^3.1.1",
|
||||
"nexrad-level-2-data": "file:../nexrad-level-2-data",
|
||||
"svgdom": "^0.1.8"
|
||||
},
|
||||
"devDependencies": {
|
||||
"eslint": "^8.0.0",
|
||||
"eslint-config-airbnb-base": "^15.0.0",
|
||||
"eslint": "^7.32.0",
|
||||
"eslint-config-airbnb-base": "^14.2.1",
|
||||
"eslint-plugin-import": "^2.23.4",
|
||||
"glob": "^7.1.7"
|
||||
},
|
||||
|
||||
+103
-60
@@ -1,15 +1,8 @@
|
||||
const canvasObj = require('canvas');
|
||||
const { createSVGWindow } = require('svgdom');
|
||||
|
||||
const { createCanvas } = canvasObj;
|
||||
const { SVG, registerWindow } = require('@svgdotjs/svg.js');
|
||||
|
||||
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 = {
|
||||
@@ -44,7 +37,29 @@ const DEFAULT_OPTIONS = {
|
||||
lineWidth: 2,
|
||||
};
|
||||
|
||||
// calculation constants
|
||||
const RAD45 = (45 * Math.PI / 180);
|
||||
const RAD90 = RAD45 * 2;
|
||||
|
||||
// round to specified number of decimal points
|
||||
const roundTo = (decimals, value) => Math.round(value * 10 ** decimals) / 10 ** decimals;
|
||||
|
||||
// polar to cartesean conversion
|
||||
const polarToCartesean = (r, theta) => {
|
||||
const x = roundTo(2, r * Math.cos(theta));
|
||||
const y = roundTo(2, r * Math.sin(theta));
|
||||
return {
|
||||
x, y,
|
||||
};
|
||||
};
|
||||
|
||||
const draw = (data, _options) => {
|
||||
// create a new window
|
||||
const window = createSVGWindow();
|
||||
const { document } = window;
|
||||
// register window and document
|
||||
registerWindow(window, document);
|
||||
|
||||
// combine options with defaults
|
||||
const options = {
|
||||
...DEFAULT_OPTIONS,
|
||||
@@ -60,19 +75,10 @@ const draw = (data, _options) => {
|
||||
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);
|
||||
// create the canvas
|
||||
const canvas = SVG(document.documentElement);
|
||||
canvas.size(cropTo, cropTo);
|
||||
canvas.viewbox(-cropTo / 2, -cropTo / 2, cropTo, cropTo);
|
||||
|
||||
// get the palette
|
||||
const palette = palettes[options.product];
|
||||
@@ -86,7 +92,7 @@ const draw = (data, _options) => {
|
||||
|
||||
// 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;
|
||||
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;
|
||||
|
||||
@@ -101,59 +107,96 @@ const draw = (data, _options) => {
|
||||
// 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);
|
||||
const paths = {};
|
||||
|
||||
// loop through data
|
||||
rrlEncoded.forEach((radial) => {
|
||||
// calculate plotting parameters
|
||||
const deadZone = radial.first_gate / radial.gate_size / scale;
|
||||
headers.forEach((header) => {
|
||||
// get correct data
|
||||
const thisRadial = header[dataName];
|
||||
// skip if this radial isn't found
|
||||
if (thisRadial === undefined) return;
|
||||
|
||||
// 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;
|
||||
// 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
|
||||
radial.moment_data.forEach((bin, idx) => {
|
||||
for (let idx = 0; idx < maxBin; idx += 1) {
|
||||
// get the value
|
||||
const bin = thisRadial.moment_data[idx];
|
||||
// skip null values
|
||||
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), startAngle, endAngle + resolution * (bin.count - 1));
|
||||
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 {
|
||||
// plain data
|
||||
ctx.strokeStyle = palette.lookupRgba[bin];
|
||||
ctx.arc(0, 0, (idx + deadZone), startAngle, endAngle);
|
||||
thisSample = bin;
|
||||
}
|
||||
|
||||
// see if there's a sample to plot
|
||||
if (thisSample && !palette.inDeadband(thisSample)) {
|
||||
// get color
|
||||
const color = palette.findColorRgba(thisSample);
|
||||
|
||||
if (!paths[color]) paths[color] = [];
|
||||
|
||||
// calculate radius
|
||||
const r = (idx + deadZone) / scale;
|
||||
const rRounded = roundTo(2, r);
|
||||
|
||||
// calculate start of arc
|
||||
const arcStartCartesean = polarToCartesean(r, startAngle);
|
||||
paths[color].push(['M', arcStartCartesean.x, arcStartCartesean.y]);
|
||||
|
||||
// calculate end of arc
|
||||
const arcEndCartesean = polarToCartesean(r, endAngle);
|
||||
|
||||
// end of arc and flags
|
||||
paths[color].push(['A', rRounded, rRounded, 0, 0, 0, arcEndCartesean.x, arcEndCartesean.y]);
|
||||
}
|
||||
ctx.stroke();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
// draw each path
|
||||
Object.entries(paths).forEach(([color, path]) => {
|
||||
path.push('z');
|
||||
canvas.path(path.flat()).stroke({ color });
|
||||
});
|
||||
|
||||
if (!options.palettize) {
|
||||
// return the palette and canvas
|
||||
return {
|
||||
canvas,
|
||||
};
|
||||
}
|
||||
|
||||
// palettize image
|
||||
const palettized = palettizeImage(canvas.getContext('2d'), palette);
|
||||
|
||||
// return palettized image
|
||||
return {
|
||||
canvas: palettized,
|
||||
palette: palette.getPalette(),
|
||||
canvas,
|
||||
};
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
draw,
|
||||
DEFAULT_OPTIONS,
|
||||
canvas: canvasObj,
|
||||
};
|
||||
@@ -12,7 +12,6 @@ class Palette {
|
||||
this.limits = palette.limits;
|
||||
this.transparentIndex = palette.transparentIndex;
|
||||
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
|
||||
@@ -34,9 +33,9 @@ class Palette {
|
||||
}
|
||||
}
|
||||
|
||||
findColorIndex(dbz) {
|
||||
findColorRgba(dbz) {
|
||||
// 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() {
|
||||
@@ -85,23 +84,14 @@ class Palette {
|
||||
}
|
||||
}
|
||||
|
||||
// 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, 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);
|
||||
lookupRgba.push(`rgba(${palette[index * 4]},${palette[index * 4 + 1]},${palette[index * 4 + 2]},${palette[(index * 4 + 3)] / 255})`);
|
||||
}
|
||||
return lookupRgba;
|
||||
};
|
||||
|
||||
@@ -6,6 +6,7 @@ const palettizeImage = (sourceCtx, palette) => {
|
||||
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,10 +19,11 @@ 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);
|
||||
|
||||
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
+2
-1
@@ -1,5 +1,5 @@
|
||||
const { draw, canvas } = require('./draw');
|
||||
const { writePngToFile } = require('./utils/file');
|
||||
const { writePngToFile, writeSvgToFile } = require('./utils/file');
|
||||
/**
|
||||
* Plot level 2 data
|
||||
* @param {Level2Data} data output from the nexrad-level-2-data library
|
||||
@@ -44,5 +44,6 @@ const plot = (data, _products, options) => {
|
||||
module.exports = {
|
||||
plot,
|
||||
writePngToFile,
|
||||
writeSvgToFile,
|
||||
canvas,
|
||||
};
|
||||
@@ -26,6 +26,18 @@ const writePngToFile = (fileName, data) => new Promise((resolve, reject) => {
|
||||
writeStream.on('error', (e) => reject(e));
|
||||
});
|
||||
|
||||
const writeSvgToFile = async (fileName, data) => {
|
||||
// the draw function will return false if no data was found, short circuit the output here
|
||||
if (!data.canvas) {
|
||||
return;
|
||||
}
|
||||
|
||||
// write to the stream
|
||||
await fs.promises.writeFile(fileName, data.canvas.svg());
|
||||
console.log(fileName);
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
writePngToFile,
|
||||
writeSvgToFile,
|
||||
};
|
||||
Reference in new issue
Block a user