Skip to content

plotSpectra — spectra from LAVA probe and FW-H records

Computes and plots PSD, narrow-band SPL, 1/n-octave band levels, OASPL and directivity from the binary LAVAMonitor .iter files LAVA writes: point and line probes and monitor histories (monitor/*.data.iter) as well as the streaming FW-H observer records (fwh/fwh.<name>.iter). Any column of any .iter file is a signal to it; time, an optional ctu column and one column per probe or observer. Groups of observers replicated in azimuth (FW-H rings) can be power averaged, rotor phase-lock averaged or decomposed into azimuthal modes, and spectra of any origin are overlaid on the same axes for comparison with experiments and other runs.

Three ways to use it, all shipped in the one plotSpectra.pyz:

Command line (plotHist-style) plotSpectra.pyz probe1 probe2 -F monitor/Unst.data.iter -df 10 -logx
YAML input driver for several figures plotSpectra.pyz -input plots.yml (see YAML input driver)
User API in your own script plotSpectra.pyz -run myplots.py or from plotspectra import ... (see User API)

plotSpectra.pyz is installed with LAVA next to plotHist.py. It is one file: copy it anywhere, it needs Python 3.9+ and fetches numpy, matplotlib and PyYAML into a per-user environment on its first run. plotSpectra.pyz -h lists every option; the subcommands (convert-digitized, convert-tecplot, digitize, psdobs) have their own -h.

Getting started

plotSpectra.pyz -createSampleData sample        # a dataset to try everything on
cd sample && cat README.txt

The sample is a synthetic two-blade rotor at 5400 rpm heard by two microphones, each replicated at 12 azimuths: fwh/fwh.rotor.iter (the record, as the solver writes it), observers.txt, an "experimental" narrow-band spectrum experiment_SPL_df5Hz.dat, and the same comparison figure driven the three ways, plot.sh, plots.yml and plot.py:

plotSpectra.pyz -F fwh/fwh.rotor.iter -dispVars                                  # what is in the record
plotSpectra.pyz mic1_a000 -F fwh/fwh.rotor.iter -df 5 -logx                      # one observer
plotSpectra.pyz 'mic1_a*' -F fwh/fwh.rotor.iter -powerAverage -spread -mode spl -df 5 -logx -fRange 50 10000
./plot.sh                                      # both microphones against the experiment, command line
plotSpectra.pyz -input plots.yml               # the same from an input file (-dryRun prints the command lines)
plotSpectra.pyz -run plot.py                   # the same from a script using the library

Replace the sample's files by your own .iter record and your own table and the three drivers carry over unchanged.

Command line

plotSpectra.pyz [observers ...] -F FILE [-F FILE2 ...] [options]

Selecting data

option meaning
observers names or glob patterns ('m1_a*', m1_a000,m2_a090); default: all observers
-F FILE .iter file; repeat to overlay several runs (legend = dir/file:observer)

Styling your own curves. A selection or a -F file may carry key=value style tokens after the pattern or path, the same keys as -compare: color, ls, lw, marker, ms, every, label (quote values with spaces: label="LAVA M1"). Symbols instead of a line: ls=none marker=o ms=4; on dense curves thin them with every=20 (one marker per 20 points).

plotSpectra.pyz 'm1_a000 color=b ls=- label=in-plane' 'm3_a000 color=r ls=-- label=45deg' -F fwh/fwh.s.iter
plotSpectra.pyz 'm1_a000 ls=none marker=o ms=3 every=10 label=symbols' -F fwh/fwh.s.iter
plotSpectra.pyz 'm1_a*' -powerAverage -F 'coarse/fwh/fwh.s.iter color=0.5 label=coarse' \
                                     -F 'fine/fwh/fwh.s.iter color=k label=fine'

Two runs rarely reach a statistically steady state at the same time, so a file may also carry its own signal window, t=T0:T1 in seconds or ctu=C0:C1 in convective time units, in place of -tRange / -ctuRange for that file. An end left out is the record's (ctu=200: from 200 to the end):

plotSpectra.pyz 'deg090_*' -powerAverage -F 'run1/fwh/fwh.tri.iter ctu=150:350 label=run1' \
                                         -F 'run2/fwh/fwh.tri.iter ctu=220: label=run2'

The summary prints the span each file used. In a YAML input file the window goes with the record: run2: 'run2/fwh/fwh.tri.iter ctu=220:'.

A file style applies to every curve from that file and its label replaces the dir/file legend prefix; a selection style applies to the curves it picked (also to the group it forms with -powerAverage) and overrides the file style. A selection label is used alone when the selection produced one curve, otherwise as label:observer. | -dispVars | list the observers, sample rate and time span of each file, then exit | | -tRange T0 T1, -ctuRange C0 C1 | part of the record to use (seconds, or convective time units from the ctu column); a file's own t= / ctu= in its -F wins (below) |

What to plot

-mode curve
psd (default) power spectral density: dB/Hz re 20 µPa (-db, default) or Pa²/Hz (-linear)
spl narrow-band level = PSD·Δf per bin, dB or Pa² (the old pyPost "SPL")
octave 1/-octave N band levels (default 1/3), base-2 ratios (-octaveBase10 for base 10)
time the pressure signals, mean removed
directivity band-limited OASPL versus angle (see Directivity)
option meaning
-fRange FMIN FMAX plot limits and the band for OASPL, directivity and octave bands (does not change the estimate)
-aWeight A-weighting (IEC 61672)
-pref P reference pressure for dB (default 20e-6 Pa)

Frequency axis

-xaxis x
hz (default) f in Hz
st Strouhal f·L/U from -stLength L -stVelocity U, else f·T_ref with the reference time recovered from the ctu column (or -refTime T)
fref f / f_ref with -fref F (any reference frequency)
bpf f / BPF with -rpm R -blades N (BPF = R·N/60 Hz, e.g. 5400 rpm × 2 blades = 180 Hz); the harmonics then sit at 1, 2, 3, …

A PSD is a density, so it depends on what it is per. -density hz (the default in dB) keeps dB per Hz on any axis; -density st re-expresses it per unit of the chosen axis (per St, per f/f_ref, per f/BPF; the integral over the axis is preserved), which is how the NASA jet-noise sets are given ("PSD per unit Strouhal number": 10·log10(U/D) above the per-Hz value, about 38 dB for a 2-inch Mach 0.9 jet). -linear has always been per unit of the axis; -density hz makes it per Hz. Comparison tables (-compare) always hold per-Hz densities and are converted the same way, so one file serves both views.

Welch controls

option meaning default
-df 10 frequency resolution in Hz → segment length fs/df samples; -df match takes the bin width of the first -compare spec with df= whole record (one segment)
-nperseg N segment length in samples
-nseg K number of overlapping segments (windows); length and df follow from the record and the overlap
-overlap 0.5 overlap fraction, 0 ≤ x < 1 0.5
-window hann hann, hamming, blackman, blackmanharris, flattop, bartlett, rectangular (periodic forms) hann
-detrend 0 polynomial trend removed from the whole record: 0 mean, 1 linear, none 0
-segDetrend none extra per-segment detrend constant / linear (scipy style); none keeps content slower than a segment, like the old pyPost tool none
-fs F resample to this rate first (non-uniform records are resampled automatically) record rate

Give only one of -df, -nperseg, -nseg; the number of segments is 1 + floor((N − nperseg) / (nperseg·(1 − overlap))) and is printed in the summary line (Welch: nperseg = ..., df = ..., segments = ..., window = ... (ENBW ...), overlap = ...). A smaller df resolves lower frequencies and finer lines but leaves fewer segments and a noisier estimate; more segments smooth the estimate but coarsen df. The old pyPost call getPSD(var, tStart, tEnd, fs, binFreq, overlap) maps to -tRange tStart tEnd -fs fs -df binFreq -overlap overlap with the default detrend.

Azimuthal copies of a microphone

Grouping. Copies are grouped by their names in the record, not by the observer file. -groupBy chooses the rule; the summary lists the groups and their sizes.

-groupBy rule azimuth of each copy
name <group>_a<angle> names: m1_a090 → group m1, azimuth 90 (-groupRegex for other conventions) from the name
pattern every selection argument on the command line is one group: 'm1_a*' 'm2_a*' → two groups; obs1,obs2,obs3 → one from the observer file if given, else unknown
geometry observers with the same radius and elevation about -axis in the -observers file form a ring from the observer file
auto (default) name if any selected name matches the regex (the others stay single), else geometry if an observer file is given, else pattern

What is computed — three different questions:

option what it computes when it is the right thing
-powerAverage power average of the copies' PSDs, one curve per group; -spread shades the min/max envelope and the summary prints the copy-to-copy spread the default choice: the copies are independent realizations of a statistically axisymmetric field, so averaging the power lowers the estimate variance like more Welch segments, for tones and broadband alike. Phases, and hence the rotation rate, play no role. This is what the old averageData… script did for the jet arrays.
-azSync RPM (-azSyncAuto) rotor phase-locked (synchronous) average: each copy is shifted in time by azimuth/Ω and the copies are averaged → the rotor-locked tonal signal; the residuals give the broadband spectrum; the summary prints the tonal share of the mean-square rotors only, when you want the tonal/broadband split. RPM is signed with the sense in which the azimuth angle increases; -azSyncAuto tries both senses and keeps the better. Needs the azimuth of every copy.
-azModes M PSD of the azimuthal Fourier modes m = −M…M of the ring (m = 0 axisymmetric, ±m helical co-/counter-rotating with the azimuth angle); the modes sum to the ring average jets: which modes radiate; rotors: harmonic n of a B-bladed rotor lives in mode m = nB only, a clean check of the record. Needs a uniform full ring with known azimuths: from m1_a090-style names or the -observers file; a pattern group without a geometry is refused, since its copies would only be numbered in file order.

Averaging the raw time signals without the phase shift is deliberately not offered: it is the m = 0 mode and cancels everything that rotates.

Directivity

  • -mode directivity alone plots the band-limited OASPL of every observer against the azimuth angle taken from its name, one curve per group (polar plot; -cartesianDirectivity for level versus angle).
  • With -powerAverage -observers observers.txt every group is placed at the elevation (rotor convention) or polar angle (-angleKind polar, jet convention) of its copies about -axis / -origin, giving the classic OASPL-versus-angle plot from azimuth-averaged levels. Elevation is positive toward +axis (polar angle 0); give the axis as -1,0,0 if your convention counts the downwash side negative.

The observer file is the FW-H observers file (x, y, z[, name] per line). Names are matched case-insensitively (the file may say M1_a000, the record m1_a000).

Output

option meaning
-saveFig NAME write NAME.png (no window unless -show); -dpi
-dumpData FILE write the plotted curves as a Tecplot-style ASCII table (format below)
-noPlot compute and print only
-quiet no summary table
-fontSize 14, -legendSize 12 font size of axis and tick labels, and of the legend (default legend = fontSize − 2)
-noInfo drop the small "Welch: df = …, segments …" note in the figure corner
-logx -logy -xscale k -yscale k -yRange Y0 Y1 -doSubplot -legend ... -title ... plot cosmetics
-input FILE [-dryRun] [-only NAME ...] figures described in a YAML file, see YAML input driver
-run SCRIPT [ARG ...] run your own script with the library importable, see User API

Dump format. -dumpData writes a Tecplot-readable ASCII table: # comment lines stating the quantity and units, a TITLE, a VARIABLES line that names the columns, a ZONE line, then one row per frequency. The first column is the frequency axis in the plotted unit (f_Hz, St or f_over_fref), followed by one column per curve named after the curve (observer, group, m1 tonal, m1 m=+2, ...), in the plotted quantity (e.g. PSD in dB/Hz, SPL in dB per bin):

# plotSpectra psd (PSD dB/Hz re 2e-05 Pa): first column = f_Hz, then one column per curve
TITLE = "plotSpectra psd (PSD dB/Hz re 2e-05 Pa)"
VARIABLES = "f_Hz" "m1" "m3"
ZONE T = "spectra.dat", I = 7347
0.0000000000e+00 5.6922486728e+01 5.6899857066e+01
...

Curves on different frequency grids (e.g. two files with different Δf) get their own f_Hz_<curve> column each.

Every run prints, per observer or group, the band-limited OASPL from the PSD, the share of the total power inside the band, the overall level straight from the time signal (a consistency check: they agree when no band is set), the peak frequency and its level.

Examples

# any .iter file: a point probe's pressure from the monitor history
plotSpectra.pyz probe_p1 -F monitor/Unst.data.iter -df 10 -logx
# FW-H observer records
plotSpectra.pyz -F fwh/fwh.rotor.iter -dispVars
plotSpectra.pyz m1_a000 m1_a090 -F fwh/fwh.rotor.iter -df 5 -logx -fRange 20 5000
plotSpectra.pyz 'm1_a*' -F fwh/fwh.rotor.iter -mode octave -octave 3 -fRange 20 20000 -saveFig m1_oct
plotSpectra.pyz m1_a000 -F run1/fwh/fwh.s.iter -F run2/fwh/fwh.s.iter -xaxis fref -fref 90
plotSpectra.pyz m1_a000 -F fwh/fwh.rotor.iter -linear -xaxis st -dumpData psd_st.dat

# azimuthal copies
plotSpectra.pyz 'm1_a*' 'm3_a*' -F fwh/fwh.rotor.iter -powerAverage -spread -df 20 -logx -fRange 45 5000
plotSpectra.pyz 'obs*' -F fwh/fwh.ring.iter -powerAverage -groupBy pattern -df 20
plotSpectra.pyz -F fwh/fwh.ring.iter -powerAverage -groupBy geometry -observers observers.txt -axis z
plotSpectra.pyz 'm1_a*' -F fwh/fwh.rotor.iter -azSync 5400 -azSyncAuto -df 20 -fRange 45 2000
plotSpectra.pyz 'm1_a*' -F fwh/fwh.rotor.iter -azModes 4 -df 22.5 -fRange 45 500
plotSpectra.pyz -F fwh/fwh.rotor.iter -mode directivity -powerAverage -observers observers.txt -axis x -fRange 45 5000

Comparing with experimental data

The approach is always the same: bring every dataset into one table format, then make the simulation match the experiment in quantity, bin width, frequency axis, distance and observer set, never the other way round. The tool has the time signal and can recompute its spectrum any way the experiment was reduced; the experiment is a published curve and cannot be re-reduced.

The table format

-compare SPEC overlays curves from an ASCII table in the same format — a -dumpData file from another run, or experimental spectra: frequency in Hz in the first column, one curve per further column, names from the VARIABLES line (a header-less numeric table gets col2, col3, ...). Repeat -compare for several files. Each SPEC carries its own selection and styling:

-compare 'FILE [vars=A+B] [color=k+r] [ls=--] [lw=1.2] [marker=o] [label=exp] [df=5]'   # long form
-compare 'FILE:vars:color:ls:label:df'                                                    # short form
key meaning default
vars=A+B columns to overlay (+ or , separated) all columns, or -compareVars
color=k+r matplotlib colors, one per variable or one for all (k, red, 0.4, #1f77b4) matplotlib cycle
ls=-- line style -, --, -., :; none draws the markers only --
lw=1.2 line width 1.0
marker=o marker (o, s, ^, x, +, ., ...) none
ms=4 marker size in points 3
every=20 one marker every N points (thins the symbols on dense data) every point
label=exp legend label (used alone for one variable, as exp:var for several) file name, or -compareLabel
df=5 the file holds narrow-band SPL at this bin width [Hz] -compareDf, else none
panel=NAME with -doSubplot: draw on the panel of the curve labelled NAME (a selection label=, or the resolved name) first panel

Short-form fields may be left empty: exp.dat:mic1+mic2:k:-- or exp.dat::::exp:5. The globals -compareVars, -compareDf, -compareLabel (one per file, in order) are the defaults for specs that do not set them.

Curves on their own frequency grids. A curve may bring its own frequency column named f_Hz_<curve> (the form -dumpData writes for curves on different grids and the form convert-digitized produces from digitizer output with f, level column pairs). -compare uses it when present and falls back to the first column otherwise; shorter curves are NaN-padded.

Getting a dataset into the format

Whatever the source, the result is one ASCII table, frequency in Hz first, one column per curve, in the units the file states. Four ways to get there:

A curve digitized from a figure. Most published spectra are only available as a plot. plotSpectra.pyz digitize fig.png -xcal 100:px1 10000:px2 -ycal 0:py1 70:py2 -color blue -logx -name M1 -out m1.dat extracts a curve of a given colour from a PNG, pixel by pixel, after you give it two ticks per axis (value:pixel, -logx for a logarithmic axis); plotSpectra.pyz convert-digitized digitized.csv exp.dat -names M1 M3 turns the output of any plot digitizer (pairs of f, level columns, one pair per curve, comma or whitespace separated) into the table, every curve on its own frequency column. Note the bin width the authors used; it goes on the -compare spec as df=. Expect ±1 dB at peaks and ±1.5 dB on the floor from the digitizing itself, and thin dense point sets with every= when plotting symbols.

Tecplot block files, e.g. the NASA jet-noise sets. The consensus / SHJAR set-point files (D2a_SP7.dat and friends: variables Log(St), Polar angle, PSD (dB), St; one row of Strouhal points per polar angle; PSD per unit Strouhal number, lossless, at 100 jet diameters) are converted by plotSpectra.pyz convert-tecplot into one table with an f_Hz column and one PSD column per polar angle (a050 … a160, angle from the jet inlet axis, dB/Hz):

plotSpectra.pyz convert-tecplot D2a_SP7.dat D2a_SP7_psd.dat -refTime 1.63871e-4            # the run's D/U
plotSpectra.pyz convert-tecplot D2a_SP7.dat D2a_SP7_psd.dat -velocity 310 -length 0.0508 -rObs 50

The Strouhal axis is mapped to Hz with the run's D/U (-refTime, the T_ref plotSpectra prints, or -velocity/-length), the per-St level becomes per Hz (+10·log10(T_ref)), missing bins (-999) become NaN, and -rObs (observer distance in diameters) applies the spherical spreading shift from the file's 100 D. Overlay it on the ring at the same polar angle:

plotSpectra.pyz 'deg055_*' -F fwh/fwh.tri.iter -powerAverage -mode psd -df 100 -logx \
    -compare 'D2a_SP7_psd.dat vars=a055 color=k ls=none marker=o ms=3 label=experiment'          # dB/Hz vs Hz
plotSpectra.pyz 'deg055_*' -F fwh/fwh.tri.iter -powerAverage -mode psd -df 100 -xaxis st -density st -logx \
    -compare 'D2a_SP7_psd.dat vars=a055 color=k ls=none marker=o ms=3 label=experiment'          # per St vs St, as the NASA plots

Another LAVA run. -dumpData run1.dat writes the plotted curves of one run as a table; a later run overlays it with -compare 'run1.dat label=run1'. Curves computed at a different Δf carry their own frequency column and are handled like any other table.

Legacy post-processor output. plotSpectra.pyz psdobs ... turns the spectra written by the old FW-H post-processor (PSDObs.sampleNN.dat: frequency, then one column per observer with the azimuthal copies of each polar point as the fast index) into this table format. It averages the mean-square values over the sample files and over the -ncirc copies (the legacy averaging, with the copy-to-copy spread reported), applies the Hann recovery factor (-coef, default √(8/3) as in averageDataNewWithOctaveBands_correct.py), drops the leading bins (-skip, default 2) and writes the same quantities plotSpectra plots: -mode psd|spl|octave, -db/-linear, -xaxis hz|st|fref|bpf (with -stLength/-stVelocity, -fref, -rpm/-blades), -fRange, -aWeight; -perAzimuth adds every copy as <name>_aXXX, -oaspl writes the band-limited OASPL per polar angle, -saveFig a quick look. With the legacy settings it reproduces the old *_tec.dat PSD columns to 1e-9 dB.

plotSpectra.pyz psdobs -F 'PSDObs.sample*.dat' -ncirc 36 -names M1 M3 -angles 0 45 -mode spl -o legacy_spl
plotSpectra.pyz 'm1_a*' -F fwh/fwh.rotor.iter -powerAverage -mode spl -df match -xaxis bpf -rpm 5400 -blades 2 \
    -compare 'legacy_spl.dat vars=M1 df=8 ls=none marker=o ms=2 every=3 label=legacy'

Same quantity and the same bin width

The comparison data are plotted as the same quantity as the tool's curves. Experimental data are usually narrow-band SPL at a stated bin width; with df= the tool converts: to PSD in dB/Hz it subtracts 10·log10(df), to SPL at its own Δf it adds 10·log10(Δf / df). Without df= the file is taken to hold the plotted quantity already (PSD in dB/Hz when plotting PSD).

A narrow-band spectrum depends on its bin width in two opposite ways. Broadband power is spread evenly, so its level per bin grows with Δf (+10·log10 Δf) while its PSD (per Hz) does not depend on Δf. A tone puts all its power into one bin (about 1.5 with a Hann window), so its level per bin is the tone level whatever Δf is, while its PSD peak falls as 1/Δf. No single correction therefore makes both agree between two different bin widths: converting SPL at 5 Hz to PSD lines up the broadband and leaves the tool's tone peaks 10·log10(Δf/5) dB low.

Since the tool has the time signal, the clean answer is to compute with the experiment's Δf: -df 5 (or -df match, which takes the bin width from the first -compare spec with df=) and -mode spl, so both curves are SPL per 5 Hz bin with no conversion at all. The price is fewer Welch segments (a 0.23 s record gives one 5 Hz segment), i.e. a noisier broadband estimate, which is exactly the trade-off the experiment also faced with its record length. Interpolating a spectrum from one Δf to another does not help: a tone captured in a 20 Hz bin cannot be redistributed into 5 Hz bins, only a new estimate from the time data can. The tool prints its Δf, segment count and window in the summary, in the figure corner (-noInfo to suppress) and in the header of every -dumpData file, and warns when a comparison's df= differs from its own.

# like for like: SPL per 5 Hz bin on both sides, no conversion
plotSpectra.pyz 'mic1_a*' -powerAverage -F fwh/fwh.rotor.iter -mode spl -df match -logx -fRange 100 10000 \
    -compare 'experiment_SPL_df5Hz.dat vars=mic1 color=k ls=-- df=5'
# broadband only: PSD, the experiment converted to dB/Hz (tone peaks will not line up)
plotSpectra.pyz 'mic1_a*' -powerAverage -F fwh/fwh.rotor.iter -mode psd -df 20 -logx \
    -compare 'experiment_SPL_df5Hz.dat vars=mic1 df=5'
# 1/3-octave bands: both sides integrated to the same bands, bin width no longer matters
plotSpectra.pyz 'mic1_a*' -powerAverage -F fwh/fwh.rotor.iter -mode octave -octave 3 -fRange 50 20000 \
    -compare 'experiment_SPL_df5Hz.dat vars=mic1 df=5'

Octave bands are the robust choice when the bin widths differ a lot or the experiment is only available in bands: both sides are integrated to the same band edges, so broadband and tones are treated alike.

Same axis, distance and weighting

  • Frequency axis. Published jet spectra are usually per unit Strouhal number against St: plot with -xaxis st -density st (-stLength/-stVelocity, or the reference time from the record) and convert the dataset to Hz with the run's D/U as shown above. Rotor spectra are often against harmonics of the blade-passing frequency: -xaxis bpf -rpm R -blades N. Keep comparison tables in Hz and let the tool scale them; the same file then serves every view.
  • Distance. Experiments are reported at a microphone radius or extrapolated to a standard distance (the NASA jet sets to 100 jet diameters, lossless). Place the LAVA observers where the microphones were, or shift the dataset by spherical spreading, 20·log10(r_data / r_obs) (-rObs of convert-tecplot does this). The tool applies no atmospheric absorption, so prefer lossless data or short distances.
  • Reference pressure and weighting. dB are re 20 µPa (-pref to change); A-weighted levels with -aWeight on both sides.
  • Record length. The lowest frequency and the number of Welch segments follow from the record: a 0.2 s record gives one segment at Δf = 5 Hz. Flush the transient before sampling (restart or startctu for FW-H surfaces, -tRange/-ctuRange here) rather than clipping afterwards.

Same observers

  • Azimuthal copies. A microphone replicated around the axis of an axisymmetric mean flow gives independent realizations: -powerAverage averages their PSDs into one curve per microphone (-spread shades the copy-to-copy band). Average powers, never complex spectra or time signals: tones of a rotor carry a phase that rotates with the observer and would cancel.
  • One panel per observer. -doSubplot with panel=<label> on each -compare spec puts every experimental curve on the panel of its simulated counterpart; the input file's sweep writes those specs for you (the sample's plots.yml).
  • Directivity. -mode directivity -powerAverage -observers observers.txt -axis x -fRange ... gives the band-limited OASPL against polar or elevation angle from the azimuth-averaged levels, the usual form of an experimental directivity plot.

When curves disagree

  1. Same quantity and same Δf on every curve? (-mode spl -df match, df= on every narrow-band file; or octave bands.)
  2. Simulation: transient flushed before sampling, record long enough for the Δf asked for? The summary prints the segment count and Δf of every curve.
  3. Dataset: units of the file (SPL per bin, PSD per Hz, per St), its bin width, distance and any correction (lossless, free-field) read from the source, not assumed.
  4. Observers at the microphone positions, azimuth copies averaged, same polar-angle convention (from the inlet axis or from the jet axis; -angleKind).
  5. Digitized curves: ±1 dB at the peaks, more on the floor; compare trends and levels, not wiggles.

Worked examples

# rotor: one microphone, 36 azimuth copies power averaged, SPL at the facility's 5 Hz bins, as symbols
plotSpectra.pyz 'mic1_a* color=b' -F fwh/fwh.rotor.iter -powerAverage -mode spl -df match -logx \
    -compare 'facility_SPL_df5Hz.dat vars=mic1 ls=none marker=o ms=3 every=25 color=k label=experiment df=5'
# the same against the harmonics of the blade-passing frequency, two runs overlaid
plotSpectra.pyz 'mic1_a*' -powerAverage -mode spl -df match -xaxis bpf -rpm 5400 -blades 2 -fRange 90 3000 \
    -F 'coarse/fwh/fwh.rotor.iter color=0.5 label=coarse' -F 'fine/fwh/fwh.rotor.iter color=k label=fine' \
    -compare 'facility_SPL_df5Hz.dat vars=mic1 color=r ls=-- df=5'
# jet: one polar angle against the NASA set point, per unit Strouhal number
plotSpectra.pyz 'deg055_*' -F fwh/fwh.tri.iter -powerAverage -mode psd -df 100 -xaxis st -density st -logx \
    -compare 'D2a_SP7_psd.dat vars=a055 color=k ls=none marker=o ms=3 label=experiment'
# every observer on its own panel from an input file: the sample's plots.yml does this with a sweep
plotSpectra.pyz -input plots.yml

YAML input driver

plotSpectra.pyz -input plots.yml reads a YAML file that describes several figures. Each figure is expanded into an ordinary command line and run through the command-line front end, so the file and the command line mean exactly the same thing; -dryRun prints those command lines instead of running them (paste one back to tweak it by hand), -only NAME ... picks figures. Paths in the file are relative to the file. All figures are shown together at the end when any of them asks for a window.

defaults:                      # CLI options for every figure: the option name without the dash,
  powerAverage: true           # `flag: true` for switches, a list for options with several values
  df: 100
  xaxis: st
  density: st
  logx: true
  fRange: [400, 50000]
records:                       # name -> .iter file, optionally with a style and window ('path label=fine ctu=200:')
  run01: fwh/fwh.tri.iter
compare:                       # name -> comparison table and its default keys (the -compare keys)
  nasa: {file: D2a_SP7_psd.dat, ls: none, marker: o, ms: 3, label: exp}
figures:
  - name: all_angles           # {name} in templates; default figure1, figure2, ...
    records: [run01]           # or record: run01 (a name from `records`, or a path)
    sweep: {angle: ["055", "090", "140"]}
    select: "deg{angle}_* color={color} lw=1.2 label={angle}deg"   # one selection per sweep value
    compare: "nasa vars=a{angle} color={color} panel={angle}deg"   # one -compare per sweep value
    doSubplot: true            # any other key is a CLI option for this figure (overrides defaults)
    saveFig: plots/{name}
    show: true
  • Sweeps. sweep maps keys to lists; select and compare entries (strings or lists of strings) are formatted once per sweep step with {key}, plus {name}, {i} (the step index) and {color} (a 23-colour cycle, matplotlib's tab20 and three dark extras). An entry without a placeholder is emitted once. Several sweep keys are zipped and must have the same length. Quote values that look like numbers: YAML reads 055 as a number.
  • Named comparisons. A compare entry whose first word is a name from the file's compare map takes that entry's keys and adds or overrides the key=value pairs that follow; anything else is passed to -compare unchanged (a file path with keys, or the short form).
  • Hiding curves from the legend. label=_nolegend_ (matplotlib skips labels starting with an underscore), useful when many experimental symbols share the colour of their simulation curve.
  • records values may carry a style the way -F does; -only with an unknown name lists the figures in the file.

The sample's plots.yml is a complete file with two figures; plotSpectra.pyz -input plots.yml -dryRun shows the commands it generates.

User API

The package is importable straight from the zipapp. The simplest route is to let the .pyz run your script, which also gives it the tool's own numpy/matplotlib environment:

plotSpectra.pyz -run myplots.py [args ...]      # sys.argv = [myplots.py, args ...], plotspectra importable

Or put the .pyz (or the checkout) on sys.path and use any python that has numpy and matplotlib. The sample's plot.py is a complete script that works both ways.

import sys; sys.path.insert(0, "/path/to/plotSpectra.pyz")     # not needed under -run
from plotspectra import read_iter, compute_spectrum, spectra_from_file, directivity, db

rec = read_iter("fwh/fwh.rotor.iter")      # rec.names, rec.time, rec["m1_a000"], rec.ref_time()
sp  = compute_spectrum(rec.time, rec["m1_a000"], df=10.0, window="hann", overlap=0.5, detrend_order=0)
sp.f, sp.psd            # Hz, Pa^2/Hz          sp.psd_db(), sp.spl, sp.spl_db()
sp.oaspl(50, 5000)      # dB re 20 uPa         sp.oaspl(a_weight=True)
sp.octave(3, 20, 20e3)  # (fc, fl, fu, band power Pa^2)
sp.scaled("st", ref_time=rec.ref_time())        # Strouhal axis + density per St

rec, spectra = spectra_from_file("fwh/fwh.rotor.iter", ["m1_a*"], ctu0=15, df=10)
angles, levels, names = directivity(spectra, fmin=50, fmax=5000)["m1"]

from plotspectra import azimuth_average, azimuth_sync, azimuth_modes, build_groups
avg    = azimuth_average(spectra)["m1"]                      # Spectrum; avg.meta["n"], ["spread_db"]
groups = build_groups(list(spectra), "pattern", patterns=["m1_a*"])   # or "geometry" with observer_angles(...)
avg2   = azimuth_average(spectra, groups=groups)["m1_a*"]    # needed for rings not named <group>_a<angle>, e.g. deg055_01
sync   = azimuth_sync(rec, spectra, rpm=5400, auto_sign=True, df=20)["m1"]   # ["tonal"], ["broadband"], ["tonal_fraction"]
modes  = azimuth_modes(rec, spectra, mmax=4, df=22.5)["m1"]  # {m: Spectrum}

Lower level: welch(x, fs, df=..., window=..., overlap=...) returns (f, psd, info); welch_segments gives the per-segment complex spectra; power_average, sync_average, azimuthal_modes, octave_bands, band_integrate, a_weighting_db, make_scale, read_observer_file, observer_angles, write_ascii, write_iter.

Conventions

  • PSD is one-sided with energy-consistent window scaling 1/(fs·Σw²) (identical to scipy.signal.welch(scaling="density")): Σ PSD·Δf = <p'²> for a stationary signal, whatever the window. Windows are the periodic (DFT-even) forms.
  • Narrow-band SPL is PSD·Δf (Pa² per bin), the convention of the previous pyPost tool with its energy-preserving (EFT) window factor. A pure tone spreads over ~1.5 bins with a Hann window; the sum over the peak bins gives the tone level, and OASPL is exact.
  • dB: 10·log10(P / pref²), pref = 20 µPa (-pref to change).
  • Band integrals treat each bin as a constant density over [f−Δf/2, f+Δf/2], so band edges and 1/n-octave bands narrower than Δf are handled consistently.
  • A-weighting: IEC 61672-1 (0 dB at 1 kHz, −19.1 dB at 100 Hz).
  • Azimuthal modes: P_m = (1/N) Σ_i X_i e^{+i m ψ_i} per Welch segment, so a pattern cos(ωt − mψ) rotating toward increasing azimuth is mode +m; the phase-locked average shifts copies by an exact Fourier phase.