Skip to main content

Power Quality

What is power quality?​

Power quality is how closely the electricity at a point in a network matches an ideal supply: a sine wave at the right voltage and frequency, balanced across the three phases and never interrupted. It is measured from the size and shape of the voltage and current, and judged by disturbances such as sags, harmonics and flicker.

A simulated three-phase supply feeding LED drivers in a dark navy theme: phase voltages with a sag on L1, peaky phase currents and a larger neutral current, a phasor diagram, half-cycle RMS traces dipping below the 90% line, and a harmonic bar chart of voltage and current in per cent of the fundamental

A simulated three-phase supply feeding LED drivers: voltage and current waveforms, phasors, the half-cycle RMS trace that catches a sag, and the harmonic spectrum (sample data). Try the interactive version.

Key takeaways
  • Power quality covers five things: voltage magnitude, frequency, waveform shape, balance between phases, and continuity of supply.
  • Sags (dips) are among the most common causes of equipment trips; they're caught with an RMS value refreshed every half cycle.
  • Harmonics come from loads that draw current in pulses. Total harmonic distortion (THD) sums them into one percentage.
  • IEEE 519 and EN 50160 set the limits; IEC 61000-4-30 and IEC 61000-4-7 say how to measure, so two analysers agree.
  • An analyser shows the same data five ways: waveforms, a harmonic bar chart, trends over days, RMS event plots and a phasor diagram.

Utilities, factories, data centres, hospitals and anyone connecting solar, wind, batteries or electric vehicle chargers to the grid all measure it.

What power quality covers​

A perfect supply is a clean sine wave that never changes. Real supplies drift from it in five ways, and every power quality problem is one of them:

PropertyIdealWhat goes wrong
Voltage magnitudeThe nominal voltage, for example 230 V or 120 V phase to neutralSlow under- or overvoltage, short sags and swells, fast fluctuations that cause flicker
FrequencyExactly 50 Hz or 60 HzSmall deviations when generation and demand don't match
Waveform shapeA pure sine waveHarmonics, interharmonics, notching, transients
BalanceThree phases of equal size, 120° apartUnbalance from uneven single-phase loads
ContinuityAlways onShort and long interruptions

The voltage is mostly the network operator's responsibility. The current is mostly the customer's: what a building's loads draw decides its current harmonics and power factor, and those currents then distort the voltage for everyone on the same feeder.

Power quality disturbances and their causes​

Power quality disturbances are grouped by how long they last and how far they move the voltage, from microsecond transients to sustained interruptions.

Nine small waveform sketches of power quality disturbances: normal supply, sag, swell, interruption, oscillatory transient, harmonic distortion, flicker, notching and three-phase unbalance

IEEE 1159 sorts disturbances by how long they last and how large they are. The table follows its categories; the thresholds are those used by most analysers.

DisturbanceWhat it looks likeTypical size and durationCommon causes
Sag (dip)RMS voltage falls but stays on10% to 90% of nominal, half a cycle to 1 minuteFaults elsewhere on the network, large motors starting, transformer energising
SwellRMS voltage rises110% to 180%, half a cycle to 1 minuteThe healthy phases during a fault from one phase to earth; large loads switching off
InterruptionVoltage near zeroBelow about 10% of nominal; up to 1 minute (momentary or temporary), or sustained beyond that. EN 50160 puts the line between short and long interruptions at 3 minutes insteadBreakers, fuses and reclosers clearing faults; planned outages
Under- and overvoltageRMS steadily too low or too highBeyond ±10% for over a minuteOverloaded or lightly loaded feeders, wrong transformer taps, solar export on a weak line
TransientA spike or ring lasting microseconds to millisecondsImpulsive (lightning) or oscillatory (switching), peaks up to several times normalLightning, capacitor bank switching, switching of inductive loads
HarmonicsA repeating, non-sinusoidal waveformDistortion at whole multiples of 50 or 60 HzNon-linear loads: rectifiers, drives, LED drivers, computer power supplies
InterharmonicsDistortion at frequencies between harmonicsUsually smallArc furnaces, cycloconverters, some drives and inverters
Flicker (voltage fluctuation)The RMS wobbles at a few hertzChanges of a fraction of a per cent to a few per cent, repeatedArc furnaces, welders, sawmills, wind turbines, any load that cycles quickly
NotchingShort dips at each switching instant of a converterEvery half cycle or more oftenThyristor and diode rectifiers commutating
UnbalancePhases of unequal size or angleA few per cent of negative-sequence voltageSingle-phase loads unevenly spread, a blown fuse in a capacitor bank
Frequency deviationCycles slightly too long or shortFractions of a hertz on big grids, more on small or islanded onesLoss of a large generator or load; weak island grids

Sags are a common reason for a process to stop, because contactors drop out and drives trip on low DC-bus voltage within a few cycles. Harmonics rarely trip anything at once; they heat transformers, cables, motors and capacitors and shorten their lives.

Voltage sags, swells and interruptions: how they're measured​

A sag is defined by two numbers: its residual voltage (the lowest RMS value reached, as a percentage of nominal) and its duration. Both come from an RMS value updated far faster than a multimeter's.

IEC 61000-4-30, the standard for power quality measurement methods, uses Urms(1/2)U_{rms(1/2)}: the RMS over one cycle, recalculated every half cycle. On each phase:

  • A dip starts when Urms(1/2)U_{rms(1/2)} falls below the dip threshold, typically 90% of the declared voltage, and ends when it rises back above the threshold plus a hysteresis, typically 2%.
  • On a three-phase system, the dip starts when the first phase drops and ends when the last phase recovers.
  • Swells use a threshold of 110%, and interruptions a threshold of a few per cent, typically 5% or 10%.

Because each value covers a whole cycle, a measured event can look up to about a cycle longer than the disturbance itself. In the demo, a five-cycle sag on a 50 Hz supply (100 ms) is reported as 110 ms.

Results from many sites are usually plotted as a scatter of residual voltage against duration, often over a grid of ranges from EN 50160 or a tolerance curve. The ITIC (formerly CBEMA) curve is the best-known tolerance curve; it shows which sags typical IT equipment should ride through.

What are harmonics in power systems?​

A harmonic is a sine wave at a whole multiple of the supply frequency, called its order: on a 50 Hz supply, the 3rd harmonic is 150 Hz, the 5th 250 Hz and the 7th 350 Hz. Any distorted waveform that repeats every cycle can be split into a fundamental and a set of harmonics, which is what a fast Fourier transform (FFT) does.

Harmonics start in the current. A linear load, such as a heater or a filament lamp, draws a current the same shape as the voltage. A non-linear load doesn't:

  • A rectifier with a smoothing capacitor charges the capacitor only near the peak of each half cycle, so it draws narrow, tall current pulses. LED drivers, computer and phone power supplies, and battery chargers without power factor correction work this way. Their current is rich in odd harmonics, including the 3rd.
  • A six-pulse rectifier, the front end of most variable-speed drives (VFDs) and many UPS systems, draws current in blocks from each pair of phases. Its harmonics fall at orders 6k±16k \pm 1: the 5th, 7th, 11th, 13th and so on. A 12-pulse rectifier cancels the 5th and 7th, leaving 12k±112k \pm 1.
  • Arc furnaces, welders and saturated transformers add harmonics, interharmonics and even orders.

The current harmonics flow back through the supply's impedance and drop a voltage at each frequency. So a building's current distortion becomes voltage distortion for the whole feeder, and a supply's impedance at each harmonic rises with the order, because its reactance is proportional to frequency.

Harmonic sequence​

In a balanced three-phase system, each harmonic also has a phase sequence:

SequenceOrdersEffect
Positive (rotates like the fundamental)1, 4, 7, 10, 13Extra heating
Negative (rotates backwards)2, 5, 8, 11, 14A torque against a motor's rotation, extra heating in motors
Zero (all phases in step)3, 6, 9, 12, 15Adds up in the neutral; circulates in delta windings of transformers

Total harmonic distortion (THD)​

Total harmonic distortion is the RMS sum of all the harmonics of a voltage or current, as a fraction of the fundamental. For a voltage with harmonic RMS values V2,V3,…V_2, V_3, \ldots and fundamental V1V_1:

THDV=V22+V32+V42+⋯+V502V1×100%\mathrm{THD}_V = \frac{\sqrt{V_2^2 + V_3^2 + V_4^2 + \cdots + V_{50}^2}}{V_1} \times 100\%

The current version, THDI\mathrm{THD}_I, uses the current harmonics. Most standards sum the harmonics up to the 40th or 50th order.

A worked example: a 230 V supply with a fundamental of 230 V, a 3rd harmonic of 6.9 V (3%), a 5th of 11.5 V (5%) and a 7th of 6.9 V (3%) has

THDV=6.92+11.52+6.92230=15.08230=6.56%\mathrm{THD}_V = \frac{\sqrt{6.9^2 + 11.5^2 + 6.9^2}}{230} = \frac{15.08}{230} = 6.56\%

Its total RMS voltage is 2301+0.06562=230.5230\sqrt{1 + 0.0656^2} = 230.5 V, almost unchanged. A voltmeter reading 230.5 V gives no hint of distortion that already takes the 5th harmonic to IEEE 519's single-harmonic limit.

Two related measures are also in use:

  • THD measured against the total RMS rather than the fundamental is sometimes used in audio. It can't exceed 100%, while the power-systems version can: the current of an LED driver without power factor correction can have a THD above 100%.
  • Total demand distortion (TDD), used by IEEE 519 for current, divides by the site's maximum demand current instead of the present fundamental. A lightly loaded building with a small, distorted current then doesn't look worse than it is.

Triplen harmonics and neutral current​

Triplen harmonics, the 3rd, 9th, 15th and other odd multiples of three, add up in the neutral of a three-phase system instead of cancelling.

Two panels. Left: the fundamental currents of phases L1, L2 and L3 are 120 degrees apart and add to zero in the neutral. Right: their third harmonics are in step and add to a neutral current three times the size of each

The fundamental currents of a balanced three-phase load are 120° apart and cancel in the neutral. The 3rd harmonic of each phase is shifted by 3×120°=360°3 \times 120° = 360°, a full turn, so all three are in step and add. The same holds for every odd multiple of three: the triplen harmonics (3rd, 9th, 15th).

So a neutral carrying single-phase non-linear loads can carry more current than any phase. With the demo's LED drivers on all three phases, each phase carries 57.5 A RMS with a 3rd harmonic of 32 A; the neutral carries 3 × 32 = 96 A of 3rd harmonic alone, and 97.7 A in all. Neutrals and the cables and transformers that feed such loads are sized for this, or derated. Triplen currents also circulate inside the delta winding of a delta-star transformer, heating it without reaching the supply side.

Power factor: displacement and distortion​

Power factor is the ratio of real power PP (watts, doing work) to apparent power SS (volt-amperes, the product of RMS voltage and current). With distortion it has two parts:

PF=PS=cos⁡φ1⏟displacement×11+THDI2⏟distortion\mathrm{PF} = \frac{P}{S} = \underbrace{\cos\varphi_1}_{\text{displacement}} \times \underbrace{\frac{1}{\sqrt{1 + \mathrm{THD}_I^2}}}_{\text{distortion}}
  • The displacement power factor, cos⁡φ1\cos\varphi_1, is the cosine of the angle between the fundamental voltage and current. Motors make the current lag; capacitors make it lead. Capacitor banks correct it.
  • The distortion factor comes from harmonic current, which adds to the RMS current but carries almost no real power. Capacitors can't correct it; filters and better rectifiers can. The formula assumes the voltage is close to a sine wave.

A worked example: a load with a displacement power factor of 0.95 and a current THD of 80% has a distortion factor of 1/1+0.82=0.7811/\sqrt{1 + 0.8^2} = 0.781, so its true power factor is 0.95×0.781=0.740.95 \times 0.781 = 0.74. A utility meter that bills on true power factor sees 0.74, not 0.95.

Flicker and grid frequency​

Flicker is the visible flickering of lighting when the voltage fluctuates by a fraction of a per cent at a few hertz. The eye is most sensitive to fluctuations of about 8.8 Hz. IEC 61000-4-15 defines a flickermeter that models a lamp, the eye and the brain, and gives two numbers: the short-term severity PstP_{st} over 10 minutes, where 1 is the level most people find irritating, and the long-term severity PltP_{lt} over 2 hours.

Grid frequency, also called utility or mains frequency, is 50 Hz in Europe, most of Asia, Africa and Australia, and 60 Hz in most of the Americas and part of Japan; Argentina, Chile, Uruguay, Paraguay and Bolivia use 50 Hz. It falls when demand exceeds generation and rises when generation exceeds demand, so it is the grid operator's real-time measure of balance. On large interconnected grids it rarely moves more than a few tenths of a hertz; EN 50160 allows ±1% for 99.5% of a year on connected European networks.

Power quality standards: IEEE 519, EN 50160 and IEC 61000​

Some standards set limits; others set measurement methods, so that every analyser gives the same answer for the same supply.

StandardWhat it setsKey numbers
IEEE 519-2022Harmonic limits at the point of common coupling (PCC) between a customer and the utilityVoltage THD 8% up to 1 kV (5% per harmonic); 5% from 1 to 69 kV (3% per harmonic). Current TDD from 5% to 20%, higher where the supply is stronger relative to the load
EN 50160:2022Voltage characteristics a European public network should deliverVoltage within ±10% of nominal for 95% of 10-minute averages in a week; THD up to 8% (up to the 40th harmonic); PltP_{lt} no more than 1 for 95% of the week; unbalance up to 2%; 50 Hz ±1% for 99.5% of a year
IEC 61000-4-30How to measure power quality parameters, in Class A (for contracts and compliance) and Class SBasic intervals of 10 cycles (50 Hz) or 12 cycles (60 Hz), aggregated to 150/180 cycles, 10 minutes and 2 hours; Urms(1/2)U_{rms(1/2)} for dips and swells; flagging of values measured during an event
IEC 61000-4-7How to measure harmonics and interharmonicsA window of 10 or 12 cycles (about 200 ms, 5 Hz between lines), synchronised to the supply; harmonic groups to the 50th order
IEC 61000-4-15The flickermeterPstP_{st} and PltP_{lt}
IEEE 1159Recommended practice for monitoring power qualityThe categories of disturbance, with typical sizes and durations

IEEE 519 is assessed statistically. The 95th percentile of 10-minute values over a week must meet the limits, and short bursts may go higher, so a single snapshot can't show compliance.

The IEC 61000-4-7 window is why the harmonic analysis uses a whole number of cycles. With exactly 10 cycles in the window, every harmonic lands on an FFT line, and a rectangular window gives exact amplitudes. A tapered window function such as Hann is only needed when the window falls out of step with the supply frequency.

How a power quality analyser displays data​

A power quality analyser samples three voltages and three or four currents thousands of times a second, computes the quantities above, logs them for days or weeks and captures waveforms when an event occurs. Its screens, and the software that reviews its recordings, show five views:

ViewWhat it showsChart type
Waveform captureA few cycles of every voltage and current, before, during and after an eventLine chart against time, phases in standard colours
Harmonic spectrumThe size of each harmonic, in volts, amps or % of the fundamental, against the standard's limitsBar chart against harmonic order
TrendRMS, THD, frequency, flicker, power and unbalance, as 10-minute or 1-minute values over daysLine chart with min/max bands over time
RMS event plotThe half-cycle RMS of each phase through a sag, swell or interruptionLine chart against time, with threshold lines
Phasor diagramThe size and angle of each phase's fundamental voltage and currentPolar chart with arrows

The phasor diagram is also the first check after connecting an analyser. Three voltages 120° apart in the right order, with each current a short way behind its voltage, mean the clamps and leads are on correctly. A current pointing the opposite way means a clamp is on backwards. SciChart.js draws it with a polar line chart; the guide to HMI and SCADA covers the control-room trend displays where power quality data often ends up.

How to reduce harmonics​

Mitigation starts with the loads, then moves to the network:

  • Line reactors or DC-link chokes in a drive smooth its current and cut the 5th and 7th harmonics noticeably, for little cost.
  • 12- and 18-pulse rectifiers cancel the lowest harmonics using phase-shifted transformer windings.
  • Active front ends replace a drive's diode rectifier with switched transistors that draw a near-sinusoidal current.
  • Passive filters are tuned capacitor-reactor branches that give harmonic currents a low-impedance path, usually tuned just below the 5th.
  • Active harmonic filters measure the load's harmonic current and inject its opposite.
  • Power factor correction inside LED drivers and power supplies keeps their current close to a sine wave. IEC 61000-3-2 limits the harmonic current of equipment rated up to 16 A per phase.

Plain power factor correction capacitors are the one fix that can make harmonics worse. With the supply's inductance, they form a parallel resonance at order hr≈Ssc/Qch_r \approx \sqrt{S_{sc} / Q_c}, where SscS_{sc} is the short-circuit power at the busbar and QcQ_c is the capacitor rating. A 0.8 Mvar bank on a 20 MVA busbar resonates at 25=5\sqrt{25} = 5: right on the 5th harmonic, which it then amplifies. Detuned banks, with a reactor in series with each capacitor, avoid this.

Power quality analyser vs power meter vs oscilloscope​

A power quality analyser measures every parameter to a standard, a power meter logs energy and power, and an oscilloscope shows raw waveforms in detail.

Power quality analyserPower meter or energy loggerOscilloscope
MeasuresEvery power quality parameter, to IEC 61000-4-30kWh, power, power factor, sometimes THDRaw waveforms at high bandwidth
RecordsWeeks of trends plus every eventLong-term energy and load profilesShort captures
Catches sags and transientsYes, with thresholds and waveform captureRarelyOnly if triggered at the right moment
Standards compliance reportsYes (EN 50160, IEEE 519)NoNo
Use it whenInvestigating trips, failures or a compliance questionSizing loads, saving energy, billingDebugging a converter or a circuit, at kHz to MHz

Common power quality measurement mistakes​

Most power quality measurement mistakes come from the wrong instrument, the wrong reference or too short a recording.

  • Using an average-responding meter. A meter that isn't true RMS reads the peaky current of rectifier loads well below its real value. Use a true-RMS meter or an analyser.
  • Judging current distortion by THD at light load. A small load current with a high THD can be harmless. IEEE 519 uses TDD, relative to the maximum demand current, for this reason.
  • Measuring for an hour. Limits apply to a week of 10-minute values, and many problems follow a daily or weekly cycle of load. Record at least a full week.
  • A harmonic window that isn't a whole number of cycles. The harmonics then fall between FFT lines and leak into their neighbours. Synchronise the window to the supply, or use a Hann window and accept wider lines.
  • Sizing the neutral for the phase current. With single-phase rectifier loads, triplen harmonics can make the neutral current the largest in the system.
  • Adding capacitors without a resonance check. Power factor correction can tune the network to a harmonic already present. Work out hrh_r first, or fit detuned banks.
  • Trusting the setup without checking the phasors. A clamp on backwards, or two phases swapped, gives wrong power, power factor and unbalance readings.

How to build a power quality analyser display in JavaScript, React or Angular​

Every time you change a setting, the demo below rebuilds the whole record and recomputes its RMS trace, phasors and harmonic spectrum. It simulates a three-phase, four-wire supply at 256 samples per cycle and computes everything in the browser: the waveforms, the Urms(1/2)U_{rms(1/2)} event trace, a phasor diagram, and the harmonics of a 10-cycle (50 Hz) or 12-cycle (60 Hz) window as IEC 61000-4-7 specifies.

Choose a Load: a resistive heater draws a clean sine, a six-pulse drive adds the 5th and 7th, and LED drivers draw narrow pulses with a strong 3rd that piles up in the neutral. Adjust the 3rd, 5th and 7th harmonic sliders, and watch the voltage spectrum cross the IEEE 519 line and the power factor fall. Lower the L3 load to unbalance the phases, switch the Mains between 50 Hz and 60 Hz, and Inject event to see a sag, swell, interruption or capacitor-switching transient in the waveforms and the RMS trace. Hover any chart to read values; the mouse wheel zooms, dragging pans and a double-click resets the view.

Here is the code for this demo. The supply simulation, the FFT and the event detection are plain JavaScript; SciChart.js draws the waveforms, the RMS trace, the harmonic bar chart and the phasors. The React and Angular versions below draw the harmonic bar chart on its own.

// A power quality analyser view with SciChart.js: three-phase voltage and current waveforms, a phasor
// diagram, an RMS event plot and a harmonic spectrum, all recomputed when the load or the supply changes
const {
SciChartSurface,
SciChartPolarSurface,
NumericAxis,
PolarNumericAxis,
EPolarAxisMode,
EAxisAlignment,
NumberRange,
EAutoRange,
EXyDirection,
ELabelPlacement,
FastLineRenderableSeries,
FastColumnRenderableSeries,
PolarLineRenderableSeries,
XyDataSeries,
HorizontalLineAnnotation,
BoxAnnotation,
ECoordinateMode,
NativeTextAnnotation,
EHorizontalAnchorPoint,
EVerticalAnchorPoint,
SciChartJsNavyTheme,
CursorModifier,
LegendModifier,
ELegendOrientation,
ELegendPlacement,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier
} = SciChart;
// or, for npm, import { SciChartSurface, ... } from "scichart"

// --- Analysis helpers (plain JavaScript, no library needed) ---

// Mixed-radix FFT for any length (here 2,560 or 3,072 samples), recursive and short rather than fast
function fft(re, im) {
const n = re.length;
if (n === 1) return;
let p = 2;
while (n % p !== 0) p++; // the smallest factor of n
const m = n / p;
const parts = [];
for (let j = 0; j < p; j++) {
const r = new Float64Array(m);
const i = new Float64Array(m);
for (let k = 0; k < m; k++) {
r[k] = re[k * p + j];
i[k] = im[k * p + j];
}
fft(r, i);
parts.push([r, i]);
}
for (let k = 0; k < n; k++) {
let sumRe = 0;
let sumIm = 0;
for (let j = 0; j < p; j++) {
const angle = (-2 * Math.PI * j * k) / n;
const [r, i] = parts[j];
const c = Math.cos(angle);
const s = Math.sin(angle);
sumRe += r[k % m] * c - i[k % m] * s;
sumIm += r[k % m] * s + i[k % m] * c;
}
re[k] = sumRe;
im[k] = sumIm;
}
}

// Harmonics of one channel over a window of whole cycles, as IEC 61000-4-7 does: 10 cycles on 50 Hz and
// 12 on 60 Hz (about 200 ms, 5 Hz between lines). Because the window holds whole cycles, every harmonic
// falls exactly on a line, so a rectangular window (no taper) gives exact amplitudes with no leakage.
// Returns the RMS amplitude and phase of harmonics 0 to maxOrder.
function harmonics(values, start, cycles, maxOrder) {
const n = cycles * SAMPLES_PER_CYCLE;
const re = Float64Array.from(values.subarray(start, start + n));
const im = new Float64Array(n);
fft(re, im);
const result = [];
for (let h = 0; h <= maxOrder; h++) {
const k = h * cycles; // the line for harmonic h
const scale = h === 0 ? 1 / n : Math.SQRT2 / n; // peak 2|X|/n, RMS = peak / sqrt 2
result.push({ rms: Math.hypot(re[k], im[k]) * scale, phase: Math.atan2(im[k], re[k]) });
}
return result;
}

// THD: the RMS of all harmonics 2 to 50, divided by the fundamental
function thd(spectrum) {
let sum = 0;
for (let h = 2; h < spectrum.length; h++) sum += spectrum[h].rms ** 2;
return Math.sqrt(sum) / spectrum[1].rms;
}

function rms(values, start, n) {
let sum = 0;
for (let i = start; i < start + n; i++) sum += values[i] * values[i];
return Math.sqrt(sum / n);
}

// Urms(1/2) from IEC 61000-4-30, used to detect dips and swells: the RMS over one cycle, refreshed every half cycle
function halfCycleRms(values) {
const half = SAMPLES_PER_CYCLE / 2;
const out = [];
for (let end = SAMPLES_PER_CYCLE; end <= values.length; end += half) {
out.push({ index: end - 1, value: rms(values, end - SAMPLES_PER_CYCLE, SAMPLES_PER_CYCLE) });
}
return out;
}

// Classify an event from the three phases' Urms(1/2), as % of nominal: a dip starts when any phase falls
// below 90% and ends when all are back above 92% (2% hysteresis); swells use 110% and 108%;
// an interruption is all three phases below 10%
function detectEvent(urms, mainsHz) {
const steps = urms[0].length;
const halfCycleMs = 1000 / mainsHz / 2;
const events = [];
const find = (name, isIn, isOut, extreme, pick) => {
let start = -1;
let worst = extreme;
for (let k = 0; k < steps; k++) {
const values = urms.map((phase) => phase[k].value);
if (start < 0 && isIn(values)) start = k;
if (start >= 0) {
worst = pick(worst, ...values);
if (isOut(values) || k === steps - 1) {
events.push({ name, durationMs: (k - start) * halfCycleMs, extreme: worst });
start = -1;
worst = extreme;
}
}
}
};
find("Interruption", (v) => v.every((x) => x < 10), (v) => v.some((x) => x >= 12), 100, Math.min);
if (!events.length) find("Dip", (v) => v.some((x) => x < 90), (v) => v.every((x) => x >= 92), 100, Math.min);
find("Swell", (v) => v.some((x) => x > 110), (v) => v.every((x) => x <= 108), 100, Math.max);
return events;
}

// --- Charts ---
const font = { fontSize: 13 };
async function createWaveChart(div, title, yTitle, legendPlacement) {
const { wasmContext, sciChartSurface } = await SciChartSurface.create(div, {
theme: new SciChartJsNavyTheme(),
title,
titleStyle: { fontSize: 14 }
});
const xAxis = new NumericAxis(wasmContext, { axisTitle: "Time (ms)", axisTitleStyle: font, labelPrecision: 0 });
const yAxis = new NumericAxis(wasmContext, {
axisTitle: yTitle,
axisTitleStyle: font,
autoRange: EAutoRange.Always,
growBy: new NumberRange(0.1, 0.1),
labelPrecision: 0
});
sciChartSurface.xAxes.add(xAxis);
sciChartSurface.yAxes.add(yAxis);
sciChartSurface.chartModifiers.add(
new CursorModifier({ showTooltip: true, showYLine: false }),
new MouseWheelZoomModifier({ xyDirection: EXyDirection.XDirection }),
new ZoomPanModifier({ xyDirection: EXyDirection.XDirection }),
new ZoomExtentsModifier({ xyDirection: EXyDirection.XDirection }),
new LegendModifier({ showCheckboxes: false, orientation: ELegendOrientation.Horizontal, placement: legendPlacement })
);
return { sciChartSurface, wasmContext, xAxis, yAxis };
}
function addLine(chart, name, colour, dashed) {
const dataSeries = new XyDataSeries(chart.wasmContext, { dataSeriesName: name, dataIsSortedInX: true, containsNaN: false });
chart.sciChartSurface.renderableSeries.add(
new FastLineRenderableSeries(chart.wasmContext, {
dataSeries,
stroke: colour,
strokeThickness: dashed ? 1.5 : 2,
strokeDashArray: dashed ? [6, 4] : undefined
})
);
return dataSeries;
}

const PHASE_COLOURS = ["#F48420", "#50C7E0", "#E36FD8"];
const PHASES = ["L1", "L2", "L3"];

// 1. Voltage waveforms, with the harmonic analysis window shaded
const voltageChart = await createWaveChart(ui.voltageDiv, "Phase voltages", "Volts", ELegendPlacement.TopRight);
const voltageSeries = PHASES.map((name, p) => addLine(voltageChart, name, PHASE_COLOURS[p], false));
const windowBox = new BoxAnnotation({ x1: 0, x2: 200, y1: 0, y2: 1, yCoordinateMode: ECoordinateMode.Relative, fill: "#FFFFFF12", strokeThickness: 0 });
const windowLabel = new NativeTextAnnotation({ x1: 200, y1: 0.02, yCoordinateMode: ECoordinateMode.Relative, text: "harmonic analysis window ", fontSize: 12, textColor: "#C8D3E8", horizontalAnchorPoint: EHorizontalAnchorPoint.Right, verticalAnchorPoint: EVerticalAnchorPoint.Top });
voltageChart.sciChartSurface.annotations.add(windowBox, windowLabel);

// 2. Current waveforms and the neutral current
const currentChart = await createWaveChart(ui.currentDiv, "Phase and neutral currents", "Amps", ELegendPlacement.TopLeft);
const currentSeries = PHASES.map((name, p) => addLine(currentChart, name, PHASE_COLOURS[p], false));
const neutralSeries = addLine(currentChart, "Neutral", "#FFFFFF", true);

// 3. Urms(1/2) event plot, with the dip and swell thresholds
const eventChart = await createWaveChart(ui.eventDiv, "RMS per half cycle (% of nominal)", "%", ELegendPlacement.BottomLeft);
eventChart.yAxis.autoRange = EAutoRange.Never;
eventChart.yAxis.visibleRange = new NumberRange(0, 130);
const eventSeries = PHASES.map((name, p) => addLine(eventChart, name, PHASE_COLOURS[p], false));
for (const { y, label } of [{ y: 90, label: "dip 90%" }, { y: 110, label: "swell 110%" }]) {
eventChart.sciChartSurface.annotations.add(
new HorizontalLineAnnotation({ y1: y, stroke: "#C8D3E8", strokeDashArray: [4, 4], strokeThickness: 1, showLabel: true, labelValue: label, labelPlacement: ELabelPlacement.TopRight, axisLabelFill: "#C8D3E8", axisFontSize: 11 })
);
}

// Zooming or panning one waveform chart moves the other; the RMS plot keeps the whole recording in view
const timeAxes = [voltageChart.xAxis, currentChart.xAxis];
for (const axis of timeAxes) {
axis.visibleRangeChanged.subscribe(({ visibleRange }) => {
for (const other of timeAxes) {
if (other !== axis && !other.visibleRange.equals(visibleRange)) other.visibleRange = visibleRange;
}
});
}

// 4. Harmonic spectrum of L1: voltage and current side by side, in % of their fundamentals
const spectrum = await SciChartSurface.create(ui.spectrumDiv, {
theme: new SciChartJsNavyTheme(),
title: "Harmonic spectrum of L1 (% of fundamental)",
titleStyle: { fontSize: 14 }
});
spectrum.sciChartSurface.xAxes.add(
new NumericAxis(spectrum.wasmContext, {
axisTitle: "Harmonic order",
axisTitleStyle: font,
visibleRange: new NumberRange(1.2, 25.8),
autoRange: EAutoRange.Never,
autoTicks: false,
majorDelta: 1,
minorDelta: 1,
labelPrecision: 0
})
);
spectrum.sciChartSurface.yAxes.add(
new NumericAxis(spectrum.wasmContext, { id: "v", axisTitle: "Voltage (%)", axisTitleStyle: { ...font, color: "#50C7E0" }, autoRange: EAutoRange.Never, labelPrecision: 1, axisAlignment: EAxisAlignment.Left }),
new NumericAxis(spectrum.wasmContext, { id: "i", axisTitle: "Current (%)", axisTitleStyle: { ...font, color: "#F5E663" }, autoRange: EAutoRange.Never, labelPrecision: 0, axisAlignment: EAxisAlignment.Right, drawMajorGridLines: false })
);
const spectrumSeries = [
{ name: "Voltage", axis: "v", offset: -0.18, fill: "#50C7E0CC", stroke: "#50C7E0" },
{ name: "Current", axis: "i", offset: 0.18, fill: "#F5E663CC", stroke: "#F5E663" }
].map(({ name, axis, offset, fill, stroke }) => {
const dataSeries = new XyDataSeries(spectrum.wasmContext, { dataSeriesName: name });
spectrum.sciChartSurface.renderableSeries.add(
new FastColumnRenderableSeries(spectrum.wasmContext, { dataSeries, yAxisId: axis, fill, stroke, dataPointWidth: 0.34, cornerRadius: 4 })
);
return { dataSeries, offset };
});
// IEEE 519's limit for any single voltage harmonic on systems up to 1 kV
spectrum.sciChartSurface.annotations.add(
new HorizontalLineAnnotation({ y1: 5, yAxisId: "v", stroke: "#50C7E0", strokeDashArray: [4, 4], strokeThickness: 1, showLabel: true, labelValue: "IEEE 519 single-harmonic voltage limit, 5%", labelPlacement: ELabelPlacement.TopRight, axisLabelFill: "#50C7E0", axisFontSize: 11 })
);
spectrum.sciChartSurface.chartModifiers.add(
new CursorModifier({ showTooltip: true, showYLine: false }),
new LegendModifier({ showCheckboxes: false, orientation: ELegendOrientation.Horizontal, placement: ELegendPlacement.BottomRight })
);

// 5. Phasor diagram: each phase's fundamental voltage and current as an arrow (length in % of nominal,
// angle measured from L1's voltage, anticlockwise)
const phasor = await SciChartPolarSurface.create(ui.phasorDiv, {
theme: new SciChartJsNavyTheme(),
title: "Phasors (fundamental)",
titleStyle: { fontSize: 14 }
});
phasor.sciChartSurface.xAxes.add(
new PolarNumericAxis(phasor.wasmContext, {
polarAxisMode: EPolarAxisMode.Angular,
visibleRange: new NumberRange(0, 360),
autoTicks: false,
majorDelta: 30,
labelPrecision: 0,
labelPostfix: "°",
drawMinorGridLines: false,
drawMajorBands: false
})
);
phasor.sciChartSurface.yAxes.add(
new PolarNumericAxis(phasor.wasmContext, {
polarAxisMode: EPolarAxisMode.Radial,
axisAlignment: EAxisAlignment.Right,
visibleRange: new NumberRange(0, 125),
autoTicks: false,
majorDelta: 25,
drawLabels: false,
drawMinorGridLines: false,
drawMajorBands: false
})
);
// An arrow from the centre to (angle, length), with a head drawn as two short barbs
function arrowPoints(angleDeg, length) {
const toXy = (a, r) => [r * Math.cos((a * Math.PI) / 180), r * Math.sin((a * Math.PI) / 180)];
const toPolar = ([x, y]) => [((Math.atan2(y, x) * 180) / Math.PI + 360) % 360, Math.hypot(x, y)];
const [tx, ty] = toXy(angleDeg, length);
const barb = (side) => toPolar([tx + 8 * Math.cos(((angleDeg + 180 + side) * Math.PI) / 180), ty + 8 * Math.sin(((angleDeg + 180 + side) * Math.PI) / 180)]);
const tip = [angleDeg, length];
const points = [[angleDeg, 0], tip, barb(25), tip, barb(-25)];
return { x: points.map((pt) => pt[0]), y: points.map((pt) => pt[1]) };
}
const phasorArrows = [];
for (const kind of ["V", "I"]) {
PHASES.forEach((name, p) => {
const dataSeries = new XyDataSeries(phasor.wasmContext, { dataSeriesName: `${kind}${p + 1}` });
phasor.sciChartSurface.renderableSeries.add(
new PolarLineRenderableSeries(phasor.wasmContext, {
dataSeries,
stroke: PHASE_COLOURS[p],
strokeThickness: kind === "V" ? 3 : 2,
strokeDashArray: kind === "I" ? [5, 3] : undefined,
interpolateLine: false // straight arrows, not arcs
})
);
const label = new NativeTextAnnotation({ x1: 0, y1: 0, text: `${kind}${p + 1}`, fontSize: 12, textColor: PHASE_COLOURS[p], horizontalAnchorPoint: EHorizontalAnchorPoint.Center, verticalAnchorPoint: EVerticalAnchorPoint.Center });
phasor.sciChartSurface.annotations.add(label);
phasorArrows.push({ kind, p, dataSeries, label });
});
}

function setData(dataSeries, x, y) {
dataSeries.clear();
dataSeries.appendRange(Array.from(x), Array.from(y));
}

// --- The controls: every change re-simulates the supply, reruns the analysis and redraws ---
let lastMains = 0;
function update(event) {
const loadType = ui.loadSelect.value;
if (event && event.target === ui.loadSelect) {
// choosing a load sets the sliders to its typical 3rd, 5th and 7th harmonics
const preset = LOADS[loadType].harmonics;
ui.h3.input.value = String(preset[3] || 0);
ui.h5.input.value = String(preset[5] || 0);
ui.h7.input.value = String(preset[7] || 0);
}
const resistive = loadType === "resistive";
for (const s of [ui.h3, ui.h5, ui.h7]) {
s.input.disabled = resistive;
s.output.textContent = resistive ? "–" : `${s.input.value}%`;
}
ui.l3.output.textContent = `${ui.l3.input.value}%`;
const mainsHz = Number(ui.mainsSelect.value);
const settings = {
mainsHz,
loadType,
h3: Number(ui.h3.input.value),
h5: Number(ui.h5.input.value),
h7: Number(ui.h7.input.value),
l3Load: Number(ui.l3.input.value) / 100,
event: ui.eventSelect.value
};
const supply = simulateSupply(settings);
const ms = Array.from(supply.time, (t) => t * 1000);

PHASES.forEach((_, p) => {
setData(voltageSeries[p], ms, supply.voltage[p]);
setData(currentSeries[p], ms, supply.amps[p]);
});
setData(neutralSeries, ms, supply.neutral);

// Urms(1/2) per phase, as % of nominal, plotted at the end of each one-cycle window
const urms = supply.voltage.map((v) => halfCycleRms(v).map(({ index, value }) => ({ index, value: (100 * value) / supply.nominal })));
urms.forEach((phase, p) => setData(eventSeries[p], phase.map((u) => ms[u.index]), phase.map((u) => u.value)));

// Harmonic analysis over the first 10 cycles (50 Hz) or 12 cycles (60 Hz), before the event
const cycles = mainsHz === 50 ? 10 : 12;
const windowMs = (1000 * cycles) / mainsHz;
windowBox.x2 = windowMs;
windowLabel.x1 = windowMs;
const vSpectra = supply.voltage.map((v) => harmonics(v, 0, cycles, 50));
const iSpectra = supply.amps.map((i) => harmonics(i, 0, cycles, 50));
const orders = Array.from({ length: 24 }, (_, k) => k + 2);
spectrumSeries.forEach(({ dataSeries, offset }, s) => {
const lines = s === 0 ? vSpectra[0] : iSpectra[0];
const percent = orders.map((h) => (100 * lines[h].rms) / lines[1].rms);
setData(dataSeries, orders.map((h) => h + offset), percent);
// both axes start at 0; the voltage axis always shows the 5% limit line
const top = Math.max(s === 0 ? 6 : 10, 1.2 * Math.max(...percent));
spectrum.sciChartSurface.yAxes.get(s).visibleRange = new NumberRange(0, top);
});

// Phasors, rotated so that L1's voltage points to 0 degrees
const reference = vSpectra[0][1].phase;
for (const { kind, p, dataSeries, label } of phasorArrows) {
const line = (kind === "V" ? vSpectra : iSpectra)[p][1];
const length = (100 * line.rms) / (kind === "V" ? supply.nominal : RATED_CURRENT);
const angle = ((((line.phase - reference) * 180) / Math.PI) % 360 + 360) % 360;
const arrow = arrowPoints(angle, length);
setData(dataSeries, arrow.x, arrow.y);
// voltage labels sit beyond the arrow tips; current labels just off their arrows
label.x1 = kind === "V" ? angle : (angle + 10) % 360;
label.y1 = kind === "V" ? length + 12 : length * 0.6;
}

// Readout for the analysis window: RMS, THD, crest factor and power factor
const n = cycles * SAMPLES_PER_CYCLE;
let activePower = 0;
let apparentPower = 0;
for (let p = 0; p < 3; p++) {
let sum = 0;
for (let i = 0; i < n; i++) sum += supply.voltage[p][i] * supply.amps[p][i];
activePower += sum / n;
apparentPower += rms(supply.voltage[p], 0, n) * rms(supply.amps[p], 0, n);
}
const v1 = rms(supply.voltage[0], 0, n);
const i1 = rms(supply.amps[0], 0, n);
let peak = 0;
for (let i = 0; i < n; i++) peak = Math.max(peak, Math.abs(supply.amps[0][i]));
const truePf = activePower / apparentPower;
const displacementPf = Math.cos(iSpectra[0][1].phase - vSpectra[0][1].phase);
const neutralRms = rms(supply.neutral, 0, n);
const thdV = 100 * thd(vSpectra[0]);
const thdI = 100 * thd(iSpectra[0]);
const events = detectEvent(urms, mainsHz);
let eventText = settings.event === "transient" ? "Transient: peak " : "No dip, swell or interruption";
if (settings.event === "transient") {
let vPeak = 0;
for (const v of supply.voltage) for (const x of v) vPeak = Math.max(vPeak, Math.abs(x));
eventText += `${(vPeak / (Math.SQRT2 * supply.nominal)).toFixed(2)} × nominal peak, RMS barely moves`;
} else if (events.length) {
eventText = events.map((e) => `${e.name}: ${e.name === "Swell" ? "max" : "residual"} ${e.extreme.toFixed(0)}% for ${e.durationMs.toFixed(0)} ms`).join("; ");
}
const thdColour = thdV > 8 ? "#FF4D4D" : thdV > 5 ? "#F5A623" : "#2ECC71";
ui.summary.innerHTML =
`L1: ${v1.toFixed(1)} V, ${i1.toFixed(1)} A RMS · ` +
`<span style="color:${thdColour}; font-weight:600">THD<sub>V</sub> ${thdV.toFixed(1)}%</span> · THD<sub>I</sub> ${thdI.toFixed(0)}% · ` +
`current crest factor ${(peak / i1).toFixed(2)} · power factor ${truePf.toFixed(2)} (displacement ${displacementPf.toFixed(2)}) · ` +
`neutral ${neutralRms.toFixed(1)} A · ${eventText}`;

// The waveforms open on cycles 6 to 22: the end of the analysis window and the whole event.
// Double-click to see the whole recording.
if (mainsHz !== lastMains) {
const cycleMs = 1000 / mainsHz;
for (const axis of timeAxes) axis.visibleRange = new NumberRange(6 * cycleMs, 22 * cycleMs);
eventChart.xAxis.visibleRange = new NumberRange(0, ms[ms.length - 1]);
lastMains = mainsHz;
}
}

for (const s of [ui.h3, ui.h5, ui.h7, ui.l3]) s.input.addEventListener("input", update);
for (const select of [ui.loadSelect, ui.mainsSelect, ui.eventSelect]) select.addEventListener("change", update);
update(null);

Key points:

  • The waveforms are FastLineRenderableSeries, one per phase and one dashed for the neutral. Each holds 7,680 samples and is redrawn in full on every change; the three time axes follow each other through visibleRangeChanged, so zooming one zooms all three.
  • The harmonic bar chart is two FastColumnRenderableSeries, voltage and current, offset either side of each order and plotted against left and right y-axes. The IEEE 519 line is a HorizontalLineAnnotation on the voltage axis.
  • The phasor diagram is a SciChartPolarSurface with an angular and a radial PolarNumericAxis. Each phasor is a PolarLineRenderableSeries of five points, the shaft and two barbs, with interpolateLine: false so the lines stay straight.
  • The FFT, harmonic analysis, power factor and dip detection are about 120 lines of plain JavaScript. For a live feed, analyse each new 10- or 12-cycle block and replace the data series' values.

See it in the demo app: JavaScript FFT spectrum analyser · React FFT spectrum analyser · Angular FFT spectrum analyser. Related techniques: the React realtime ghosted traces chart, React line chart with threshold colours, React synchronised multi-chart and React polar gauge dashboard.

Go deeper: SciChart.js line chart documentation, the column chart, the polar line chart, the horizontal line annotation, and the learning center guides to the fast Fourier transform, window functions, signal-to-noise ratio and HMI and SCADA. For the industry, see SciChart for HMI and SCADA and instrumentation.

Frequently asked questions​

What is power quality?​

Power quality is how closely the electricity at a point in a network matches an ideal supply: a sine wave of the right voltage and frequency, balanced across the phases and never interrupted. Poor power quality shows up as sags, swells, interruptions, transients, harmonic distortion, flicker and unbalance, which can trip, overheat or shorten the life of equipment.

What is total harmonic distortion (THD)?​

Total harmonic distortion is the RMS sum of all the harmonics in a voltage or current, divided by the fundamental and given as a percentage. A pure sine wave has a THD of 0%. A 230 V supply with 3% third, 5% fifth and 3% seventh harmonics has a voltage THD of the square root of 3² + 5² + 3², about 6.6%.

What is a good THD value?​

For voltage, IEEE 519 allows a THD of up to 8% on systems up to 1 kV and 5% from 1 kV to 69 kV, with no single harmonic above 5% and 3% respectively. EN 50160 also allows up to 8% on public networks in Europe. Current distortion is judged as total demand distortion (TDD), with limits from 5% to 20% depending on how strong the supply is compared with the load.

What causes harmonics in power systems?​

Harmonics come from non-linear loads, which draw current in pulses rather than as a smooth sine wave. The main sources are rectifiers: variable-speed drives, LED drivers, computer and phone power supplies, battery chargers and UPS systems. Arc furnaces and saturated transformers add more. The current harmonics then distort the voltage as they flow through the network's impedance.

What is the difference between a voltage sag and an interruption?​

In a sag, also called a dip, the voltage falls but stays on: typically to between 10% and 90% of nominal, for half a cycle up to a minute, usually because of a fault or a large motor starting elsewhere on the network. In an interruption the voltage falls almost to zero, below about 10% of nominal, because a breaker or fuse has disconnected the supply.

How do I plot a harmonic spectrum in JavaScript?​

Take an FFT of a window holding a whole number of cycles of the waveform, such as 10 cycles at 50 Hz, read the amplitude at each harmonic's line, and divide by the fundamental to get percentages. With SciChart.js, put the orders and percentages in an XyDataSeries, draw them with a FastColumnRenderableSeries, and add a HorizontalLineAnnotation for the limit. For React or Angular, wrap the same code in scichart-react or scichart-angular.

Sources​