Skip to content

Bugfix for PR #820 Added power spectral density curves at the spectrum chart #825

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 28 commits into from

Conversation

demvlad
Copy link
Contributor

@demvlad demvlad commented May 5, 2025

Bugfix for PR #820 Added power spectral density curves at the spectrum chart

Summary by CodeRabbit

  • Style

    • Corrected minor typographical errors in variable naming for improved code clarity.
    • Added a trailing comma in an object for consistency.
  • Chores

    • Made minor non-functional code improvements.

demvlad and others added 27 commits April 30, 2025 17:01
Copy link

coderabbitai bot commented May 5, 2025

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This update corrects typographical errors in the dataLoadPSD method by standardizing the spelling of the multiplier variable and adds a trailing comma to the object returned by the _psd method when no segments are processed. No changes were made to logic, control flow, or exported entities.

Changes

File(s) Change Summary
src/graph_spectrum_calc.js Fixed the spelling of multiplier (previously multipiler) in dataLoadPSD; added a trailing comma after maxNoiseIdx in the _psd method's return object when no segments are processed.

Sequence Diagram(s)

(No sequence diagram generated as the changes are typographical and do not affect control flow.)

Possibly related PRs

Suggested labels

RN: IMPROVEMENT

Suggested reviewers

  • haslinghuis

Poem

A rabbit hopped through code one day,
And found "multipiler" in the way!
With careful paws, the typo was gone,
Now "multiplier" is spelled spot-on.
Trailing commas, neat and bright—
This code now reads just right!
🐇✨


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@haslinghuis haslinghuis added this to the 4.0.0 milestone May 5, 2025
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (4)
src/graph_spectrum.js (1)

190-199: PSD is recomputed on every Y-zoom “input” event – consider throttling or caching

dataLoad() performs a full Welch PSD every time the vertical-zoom slider fires (even when the slider is just being dragged).
Although the handler is debounced at 100 ms, a large log file + 50 % overlap FFT can still block the UI for noticeable time on low-end CPUs.

If you observe jank, consider:

-          if (userSettings.spectrumType == SPECTRUM_TYPE.POWER_SPECTRAL_DENSITY) {
-            dataLoad();
-            GraphSpectrumPlot.setData(fftData, userSettings.spectrumType);
-          }
+          if (userSettings.spectrumType === SPECTRUM_TYPE.POWER_SPECTRAL_DENSITY) {
+            window.requestIdleCallback(() => {
+              dataLoad();
+              GraphSpectrumPlot.setData(fftData, userSettings.spectrumType);
+              that.refresh();
+            }, {timeout: 100});
+            return;   // skip extra refresh below – the callback will draw
+          }

(works in all Chromium-based browsers; Firefox has a ponyfill.)

src/graph_spectrum_plot.js (1)

1075-1088: Renamed parameter breaks readability; consider keeping local TICKS

You replaced the internal constant TICKS with a parameter ticks.
This works, but many call-sites still pass nothing, relying on the default.
For clarity and to avoid accidental 0 values, keep the local constant:

-GraphSpectrumPlot._drawVerticalGridLines = function (…, label, ticks = 5) {
+GraphSpectrumPlot._drawVerticalGridLines = function (…, label, ticks = 5) {
+  const TICKS = ticks;          // semantic alias

Very minor, but eases grepping.

Also applies to: 1092-1100, 1106-1107

src/graph_spectrum_calc.js (2)

112-121: Zoom→segment-size logic is reversed & typo in multipiler

multiplier = floor(1 / zoomY) makes the segment length smaller when the
user zooms out (zoomY > 1). Welch PSD benefits from more points per
segment for better resolution when zooming out.

Consider:

-const multiplier = Math.floor(analyserZoomY);
+const multiplier = Math.floor(analyserZoomY);

(and spell “multiplier”).


623-628: Shadowing outer loop index with inner i

The inner for (let i = 0; …) hides the outer i, which can be confusing
during debugging.

Rename one of them, e.g.:

-for (let i = 0; i < n_per_seg / 2; i++) {
+for (let k = 0; k < n_per_seg / 2; k++) {
   const re = fftComplex[2 * k];
   const im = fftComplex[2 * k + 1];
   magnitudes[k] = Math.hypot(re, im);
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a263152 and b3c4abf.

📒 Files selected for processing (4)
  • index.html (1 hunks)
  • src/graph_spectrum.js (2 hunks)
  • src/graph_spectrum_calc.js (4 hunks)
  • src/graph_spectrum_plot.js (10 hunks)
🔇 Additional comments (1)
index.html (1)

462-462: Confirm option value matches JavaScript mapping
Verify that the new <option value="4">Power spectral density</option> aligns with the POWER_SPECTRAL_DENSITY = 4 constant in your spectrum plotting code (e.g., graph_spectrum_plot.js) and that the event handler for spectrumTypeSelect has been updated to handle this new value.

Comment on lines +319 to +322
const WIDTH = canvasCtx.canvas.width - ACTUAL_MARGIN_LEFT;
const LEFT = canvasCtx.canvas.offsetLeft + ACTUAL_MARGIN_LEFT;
const TOP = canvasCtx.canvas.offsetTop;

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

offsetLeft/Top are 0 on off-screen canvases – translation becomes NaN

_drawPowerSpectralDensityGraph is executed first on the cached, detached
<canvas> created in _drawCachedElements.
cachedCtx.canvas.offsetLeft / offsetTop are undefined, so

const LEFT = canvasCtx.canvas.offsetLeft + ACTUAL_MARGIN_LEFT; // NaN
const TOP  = canvasCtx.canvas.offsetTop;
canvasCtx.translate(LEFT, TOP);  // ⟶ translate(NaN, undefined)

silently aborts all subsequent drawing in Chrome.

Fix: drop the DOM offsets (they are already compensated by the parent
translate in non-cached path):

-const LEFT = canvasCtx.canvas.offsetLeft + ACTUAL_MARGIN_LEFT;
-const TOP  = canvasCtx.canvas.offsetTop;
+const LEFT = ACTUAL_MARGIN_LEFT;
+const TOP  = 0;

Comment on lines +346 to +352
canvasCtx.moveTo(0, 0);
for (let pointNum = 0; pointNum < pointsCount; pointNum++) {
const freq = PLOTTED_BLACKBOX_RATE / 2 * pointNum / pointsCount;
const y = HEIGHT - (this._fftData.psdOutput[pointNum] - minY) * scaleY;
canvasCtx.lineTo(freq * scaleX, y);
}
canvasCtx.stroke();
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

The initial moveTo(0, 0) draws a stray line

moveTo(0,0) precedes the loop that starts at the first PSD point, so a
diagonal is rendered from the origin to the first data point.

Just start the path at the first point:

-canvasCtx.moveTo(0, 0);
-for (let pointNum = 0; pointNum < pointsCount; pointNum++) {
-  const freq = /* … */;
-  const y = /* … */;
-  canvasCtx.lineTo(freq * scaleX, y);
-}
+const y0 = HEIGHT - (this._fftData.psdOutput[0] - minY) * scaleY;
+canvasCtx.moveTo(0, y0);
+for (let pointNum = 1; pointNum < pointsCount; pointNum++) {
+  const freq = /* … */;
+  const y = HEIGHT - (this._fftData.psdOutput[pointNum] - minY) * scaleY;
+  canvasCtx.lineTo(freq * scaleX, y);
+}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
canvasCtx.moveTo(0, 0);
for (let pointNum = 0; pointNum < pointsCount; pointNum++) {
const freq = PLOTTED_BLACKBOX_RATE / 2 * pointNum / pointsCount;
const y = HEIGHT - (this._fftData.psdOutput[pointNum] - minY) * scaleY;
canvasCtx.lineTo(freq * scaleX, y);
}
canvasCtx.stroke();
// Start drawing at the first data point instead of (0,0)
const y0 = HEIGHT - (this._fftData.psdOutput[0] - minY) * scaleY;
canvasCtx.moveTo(0, y0);
for (let pointNum = 1; pointNum < pointsCount; pointNum++) {
const freq = PLOTTED_BLACKBOX_RATE / 2 * pointNum / pointsCount;
const y = HEIGHT - (this._fftData.psdOutput[pointNum] - minY) * scaleY;
canvasCtx.lineTo(freq * scaleX, y);
}
canvasCtx.stroke();

Comment on lines +610 to +630
GraphSpectrumCalc._fft_segmented = function(samples, n_per_seg, n_overlap) {
const samplesCount = samples.length;
let output = [];
for (let i = 0; i < samplesCount - n_per_seg; i += n_per_seg - n_overlap) {
const fftInput = samples.slice(i, i + n_per_seg);

if (userSettings.analyserHanning) {
this._hanningWindow(fftInput, n_per_seg);
}

const fftComplex = this._fft(fftInput);
const magnitudes = new Float64Array(n_per_seg / 2);
for (let i = 0; i < n_per_seg / 2; i++) {
const re = fftComplex[2 * i];
const im = fftComplex[2 * i + 1];
magnitudes[i] = Math.hypot(re, im);
}
output.push(magnitudes);
}

return output;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

No PSD segments generated when pointsPerSegment == samples.length

Termination condition uses strict <:

for (let i = 0; i < samplesCount - n_per_seg; i += n_per_seg - n_overlap)

If the log is shorter than the default 512 pts (or pointsPerSegment
was clamped to samples.length), the loop never executes, leading to
segmentsCount === 0, an empty PSD, and downstream NaNs in the plot.

Fix:

-for (let start = 0; start < samplesCount - n_per_seg; start += n_per_seg - n_overlap) {
+for (let start = 0; start <= samplesCount - n_per_seg; start += n_per_seg - n_overlap) {

Optionally guard against n_per_seg > samplesCount by reducing
n_per_seg to samplesCount.

@demvlad demvlad force-pushed the psd_spectrum_bugfix branch from b3c4abf to 69a4288 Compare May 5, 2025 20:56
@demvlad
Copy link
Contributor Author

demvlad commented May 5, 2025

Checked!
PSD_final

@demvlad demvlad marked this pull request as draft May 5, 2025 21:02
@demvlad demvlad force-pushed the psd_spectrum_bugfix branch from 69a4288 to 32b0086 Compare May 5, 2025 21:31
Copy link

sonarqubecloud bot commented May 5, 2025

@demvlad demvlad closed this May 5, 2025
@demvlad demvlad deleted the psd_spectrum_bugfix branch May 5, 2025 22:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants