# Copyright (c) 2026. Jose Manuel Requena Plens """Figures for the environmental-noise guides: outdoor propagation and exposure. Sound on its way from a source to a neighbour: atmospheric absorption, ground effect, refraction and barriers, the CNOSSOS-EU road and rail emission laws, and the exposure indices and uncertainties the assessment ends in. Everything here is embedded by a page under ``environment/``. """ import math from typing import TYPE_CHECKING, Any import matplotlib.pyplot as plt import numpy as np from numpy.typing import NDArray from phonometry._plot.common import _OFFSET_POINTS, format_frequency_axis, theme_fill from phonometry.environment import ( PassByMeasurement, ReferenceTrackCheck, SmallRoughnessDeviation, StatisticalPassByResult, ) if TYPE_CHECKING: from numpy.typing import ArrayLike from phonometry.environment import ( BinnedModulation, BinnedSoundLevels, LowFrequencyLevel, ModulationPeriod, SELDistribution, ) from phonometry.environment.sources.cnossos_road import RoadVehicleCode from .i18n import _LANG, _fmt_minus from .theme import ( COLOR_FG, COLOR_GRID, COLOR_MUTED, COLOR_PANEL, COLOR_PRIMARY, COLOR_SECONDARY, COLOR_TERTIARY, LABEL_FREQ_HZ, save_figure, ) def generate_lden_profile(output_dir: str) -> None: """A 24 h urban level profile with the Lden period weightings.""" print("Generating lden_profile.png...") from phonometry import environment hours = np.arange(24) # Typical urban road profile (synthetic hourly LAeq, dB) laeq_h = np.array( [ 48, 46, 45, 45, 46, 50, 56, 64, 66, 65, 63, 63, 64, 63, 63, 64, 65, 66, 65, 64, 63, 62, 61, 50, ], dtype=float, ) def _period_leq(idx: "np.ndarray") -> float: return float(10 * np.log10(np.mean(10 ** (0.1 * laeq_h[idx])))) ld = _period_leq(np.arange(7, 19)) # day 07-19 le = _period_leq(np.arange(19, 23)) # evening 19-23 ln_ = _period_leq(np.r_[np.arange(23, 24), np.arange(0, 7)]) # night 23-07 l_den = environment.lden(ld, le, ln_) _, ax = plt.subplots(figsize=(10, 6)) ax.axvspan(7, 19, color=theme_fill(COLOR_TERTIARY, ax)) ax.axvspan(19, 23, color=theme_fill("#e8a838", ax)) ax.axvspan(23, 24, color=theme_fill(COLOR_PRIMARY, ax)) ax.axvspan(0, 7, color=theme_fill(COLOR_PRIMARY, ax)) ax.step( np.r_[hours, 24], np.r_[laeq_h, laeq_h[-1]], where="post", color=COLOR_FG, linewidth=1.6, label=r"Hourly $L_{\mathrm{Aeq}}$", ) ax.hlines( ld, 7, 19, color=COLOR_TERTIARY, linestyle="--", linewidth=2, label=r"$L_{\mathrm{day}}$ (+0 dB)", ) ax.hlines( le + 5, 19, 23, color="#e8a838", linestyle="--", linewidth=2, label=r"$L_{\mathrm{evening}}$ + 5 dB", ) ax.hlines(ln_ + 10, 23, 24, color=COLOR_PRIMARY, linestyle="--", linewidth=2) ax.hlines( ln_ + 10, 0, 7, color=COLOR_PRIMARY, linestyle="--", linewidth=2, label=r"$L_{\mathrm{night}}$ + 10 dB", ) ax.hlines( l_den, 0, 24, color=COLOR_SECONDARY, linewidth=2.4, label=rf"$L_{{\mathrm{{den}}}}$ = {l_den:.1f} dB", ) ax.set_title(r"Day-Evening-Night Level $L_{\mathrm{den}}$ (ISO 1996-1)", pad=12) ax.set_xlim(0, 24) ax.set_ylim(42, 80) ax.set_xticks([0, 4, 7, 12, 16, 19, 23]) ax.set_xlabel("Hour of day") ax.set_ylabel("Level [dB]") ax.legend(loc="upper left", fontsize=9, ncol=2) save_figure(output_dir, "lden_profile.png") plt.close() def generate_wind_turbine_tonality(output_dir: str) -> None: """IEC 61400-11 wind-turbine tonal audibility: narrowband spectrum + masking.""" print("Generating wind_turbine_tonality...") from phonometry import environment from phonometry.environment.sources.wind_turbine import _critical_band_edges # A narrowband spectrum: a shaped broadband floor with a blade-passing-style # tone near 200 Hz, at 2 Hz resolution. df = 2.0 freqs = np.arange(50.0, 400.0 + df, df) floor = 42.0 - 6.0 * np.log10(freqs / 100.0) tone_bin = int(np.argmin(np.abs(freqs - 200.0))) levels = floor.copy() levels[tone_bin] += 22.0 res = environment.wind_turbine_tonality( levels, frequencies=freqs, tone_frequency=200.0 ) _fig, ax = plt.subplots(figsize=(10, 6)) band_lo, band_hi = _critical_band_edges(res.tone_frequency) ax.axvspan( band_lo, band_hi, color=COLOR_TERTIARY, alpha=0.15, label="Critical band" ) ax.plot( freqs, levels, color=COLOR_PRIMARY, linewidth=1.0, label="Narrowband spectrum" ) ax.axhline( res.masking_level, color="#ff7f0e", linestyle="--", linewidth=1.5, label=f"Masking level = {res.masking_level:.1f} dB", ) ax.plot( [res.tone_frequency], [res.tone_level], "o", color=COLOR_SECONDARY, markersize=9, label=f"Tone = {res.tone_level:.1f} dB", ) ax.set_xlabel("Frequency [Hz]") ax.set_ylabel("Level [dB]") ax.set_title("Wind-Turbine Tonal Audibility (IEC 61400-11)", pad=12) ax.grid(color=COLOR_GRID, linestyle="--", alpha=0.5) ax.set_axisbelow(True) ax.legend(loc="upper right", fontsize=9) ax.text( 0.02, 0.95, "Tonal audibility $\\Delta L_{\\mathrm{a}}$ = " f"{_fmt_minus(res.tonal_audibility, '.1f')} dB\n" f"{'audible' if res.is_audible else 'not audible'}", transform=ax.transAxes, va="top", fontsize=10, bbox={"boxstyle": "round", "facecolor": COLOR_GRID, "alpha": 0.6}, ) plt.tight_layout() save_figure(output_dir, "wind_turbine_tonality.svg") plt.close() def generate_air_absorption_alpha(output_dir: str) -> None: """ISO 9613-1 pure-tone atmospheric attenuation coefficient alpha(f).""" print("Generating air_absorption_alpha.png...") from phonometry import environment freqs = np.logspace(np.log10(50.0), np.log10(10000.0), 400) # Four representative (temperature, relative humidity) conditions spanning # the relaxation behaviour: the reference, a dry warm day, a cold humid day # and a hot humid day. alpha is returned in dB/m; plot in dB/km (Table 1). conditions = [ (20.0, 50.0, COLOR_PRIMARY), (20.0, 10.0, COLOR_SECONDARY), (0.0, 70.0, COLOR_TERTIARY), (30.0, 80.0, "#ff7f0e"), ] _fig, ax = plt.subplots(figsize=(10, 6.2)) for temp, rh, color in conditions: alpha_km = ( environment.air_attenuation( freqs, temperature_c=temp, relative_humidity_percent=rh ) * 1000.0 ) ax.loglog( freqs, alpha_km, color=color, linewidth=2.0, label=f"{temp:g} °C, {rh:g} % RH", ) ax.set_title(r"ISO 9613-1 Atmospheric Absorption $\alpha(f)$", pad=12) ax.set_xlabel(LABEL_FREQ_HZ) ax.set_ylabel(r"Attenuation coefficient $\alpha$ [dB/km]") ax.set_xlim(50.0, 10000.0) format_frequency_axis(ax, 50.0, 10000.0, language=_LANG) ax.grid(which="both", color=COLOR_GRID, linestyle="--", alpha=0.5) ax.legend(loc="upper left", fontsize=10) plt.tight_layout() save_figure(output_dir, "air_absorption_alpha.png") plt.close() def generate_atmospheric_attenuation(output_dir: str) -> None: """ISO 9613-1 atmospheric attenuation via the AtmosphericAttenuation.plot().""" print("Generating atmospheric_attenuation.png...") from phonometry import environment freqs = np.logspace(np.log10(50.0), np.log10(10000.0), 400) _, ax = plt.subplots(figsize=(10, 6.2)) # The result's own .plot() draws alpha in dB/km on a 1k/2k-labelled log # frequency axis for the reference 20 degC / 50 % RH atmosphere (ISO 9613-1). environment.atmospheric_attenuation( freqs, temperature_c=20.0, relative_humidity_percent=50.0 ).plot(ax=ax, language=_LANG) plt.tight_layout() save_figure(output_dir, "atmospheric_attenuation.png") plt.close() def generate_outdoor_attenuation_breakdown(output_dir: str) -> None: """ISO 9613-2 per-term octave-band attenuation breakdown, with a barrier.""" print("Generating outdoor_attenuation_breakdown.png...") from phonometry import environment bands = np.array([63.0, 125.0, 250.0, 500.0, 1000.0, 2000.0, 4000.0, 8000.0]) # A point source 200 m away over porous ground (G = 1), screened by a 4 m # barrier midway (source and receiver 1,5 m high; the diffraction geometry # gives dss = dsr ~ 100 m over the raised edge). barrier = environment.Barrier(source_to_edge=101.0, edge_to_receiver=101.0) att = environment.outdoor_propagation_attenuation( 200.0, 1.5, 1.5, frequencies=bands, ground_source=1.0, ground_middle=1.0, ground_receiver=1.0, barrier=barrier, temperature_c=15.0, relative_humidity_percent=70.0, ) x = np.arange(len(bands)) _fig, ax = plt.subplots(figsize=(11, 6.4)) # Separate positive and negative cumulative baselines so a negative term # (Agr is a net gain at 63 Hz here) stacks below zero instead of being # drawn on top of the previous bars; the signed heights sum to a_total. pos_bottom = np.zeros(len(bands)) neg_bottom = np.zeros(len(bands)) for term, color, label in [ (att.a_div, COLOR_PRIMARY, r"$A_{\mathrm{div}}$: divergence"), (att.a_atm, COLOR_TERTIARY, r"$A_{\mathrm{atm}}$: atmospheric"), (att.a_gr, "#9467bd", r"$A_{\mathrm{gr}}$: ground"), (att.a_bar, "#ff7f0e", r"$A_{\mathrm{bar}}$: barrier"), ]: bottom = np.where(term >= 0.0, pos_bottom, neg_bottom) ax.bar( x, term, bottom=bottom, color=color, edgecolor=COLOR_FG, linewidth=0.6, label=label, zorder=3, ) pos_bottom += np.maximum(term, 0.0) neg_bottom += np.minimum(term, 0.0) ax.plot( x, att.a_total, marker="D", color=COLOR_SECONDARY, linewidth=2.0, markersize=6, markerfacecolor="white", markeredgewidth=1.4, zorder=5, label="$A$: total", ) ax.set_title("ISO 9613-2 Attenuation Breakdown (with a 4 m barrier)", pad=12) ax.set_xlabel("Octave-band centre frequency [Hz]") ax.set_ylabel("Attenuation $A$ [dB]") ax.set_xticks(x) ax.set_xticklabels([f"{b:g}" for b in bands]) ax.axhline(0.0, color=COLOR_FG, linewidth=0.8, alpha=0.6) ax.grid(axis="y", color=COLOR_GRID, linestyle="--", alpha=0.5, zorder=0) ax.set_axisbelow(True) ax.legend(loc="upper left", fontsize=9, ncol=2) plt.tight_layout() save_figure(output_dir, "outdoor_attenuation_breakdown.png") plt.close() def generate_cnossos_road_emission(output_dir: str) -> None: """CNOSSOS-EU road source-line power of an urban arterial traffic mix.""" print("Generating cnossos_road_emission.png...") from phonometry import environment bands = np.array([63.0, 125.0, 250.0, 500.0, 1000.0, 2000.0, 4000.0, 8000.0]) # A two-lane urban arterial on a thin-layer surface: 1 200 light vehicles, # 90 medium heavy and 45 heavy vehicles per hour at 50 km/h, plus 60 # motorcycles, 60 m before a signalised crossing, on a 3 % upgrade, at the # 12 degC yearly mean of a temperate city. traffic = [ environment.RoadTraffic( category=environment.RoadVehicleCategory.LIGHT, flow_rate=1200.0, speed_kmh=50.0, ), environment.RoadTraffic( category=environment.RoadVehicleCategory.MEDIUM_HEAVY, flow_rate=90.0, speed_kmh=50.0, ), environment.RoadTraffic( category=environment.RoadVehicleCategory.HEAVY, flow_rate=45.0, speed_kmh=50.0, ), environment.RoadTraffic( category=environment.RoadVehicleCategory.MOTORCYCLES, flow_rate=60.0, speed_kmh=50.0, ), ] result = environment.road_source_power( traffic, surface=environment.RoadSurface.THIN_LAYER_A, temperature_c=12.0, road_slope_percent=3.0, junction_distance=60.0, junction_type=environment.JunctionType.CROSSING, ) x = np.arange(len(bands)) _fig, ax = plt.subplots(figsize=(11, 6.4)) ax.bar( x, result.total_line_power, color=COLOR_MUTED, edgecolor=COLOR_FG, linewidth=0.6, label="Total source line", zorder=2, ) labels = { "1": "Light vehicles (1)", "2": "Medium heavy vehicles (2)", "3": "Heavy vehicles (3)", "4b": "Motorcycles (4b)", } colors = [COLOR_PRIMARY, COLOR_TERTIARY, COLOR_SECONDARY, "#9467bd"] markers = ["o", "s", "D", "^"] for row, category, color, marker in zip( result.line_power, result.categories, colors, markers, strict=True ): ax.plot( x, row, color=color, marker=marker, linewidth=1.8, markersize=6, markerfacecolor="white", markeredgewidth=1.3, zorder=5, label=labels[category.value], ) ax.set_title( "CNOSSOS-EU Road Source Line Power (urban arterial, 50 km/h)", pad=12, ) ax.set_xlabel("Octave-band centre frequency [Hz]") ax.set_ylabel(r"Line power $L^{\prime}_{W,\mathrm{eq,line}}$ [dB re 1 pW/m]") ax.set_xticks(x) ax.set_xticklabels([f"{b:g}" for b in bands]) ax.set_ylim(45.0, 90.0) ax.grid(axis="y", color=COLOR_GRID, linestyle="--", alpha=0.5, zorder=0) ax.set_axisbelow(True) ax.legend(loc="lower left", fontsize=9, ncol=2) plt.tight_layout() save_figure(output_dir, "cnossos_road_emission.png") plt.close() def generate_cnossos_road_speed_law(output_dir: str) -> None: """Rolling and propulsion noise against speed, and where they cross over.""" print("Generating cnossos_road_speed_law.png...") from phonometry import environment weights = np.asarray(environment.CNOSSOS_A_WEIGHTING) def a_weighted(bands: np.ndarray) -> float: return float(10.0 * np.log10(np.sum(10.0 ** ((bands + weights) / 10.0)))) speeds = np.linspace(20.0, 130.0, 221) _fig, ax = plt.subplots(figsize=(11, 6.4)) road_categories: tuple[tuple[RoadVehicleCode, str, str], ...] = ( ("1", COLOR_PRIMARY, "Light vehicles (1)"), ("3", COLOR_SECONDARY, "Heavy vehicles (3)"), ) for category, color, name in road_categories: rolling = np.array( [a_weighted(environment.road_rolling_noise(category, v)) for v in speeds] ) propulsion = np.array( [a_weighted(environment.road_propulsion_noise(category, v)) for v in speeds] ) total = np.array( [ a_weighted(environment.road_vehicle_sound_power(category, v)) for v in speeds ] ) ax.plot( speeds, total, color=color, linewidth=2.4, zorder=5, label=f"{name}: total" ) ax.plot( speeds, rolling, color=color, linewidth=1.3, linestyle="--", zorder=4, label=f"{name}: rolling", ) ax.plot( speeds, propulsion, color=color, linewidth=1.3, linestyle=":", zorder=4, label=f"{name}: propulsion", ) crossing = int(np.argmin(np.abs(rolling - propulsion))) ax.plot( speeds[crossing], rolling[crossing], marker="o", markersize=8, markerfacecolor="white", markeredgecolor=color, markeredgewidth=1.6, zorder=6, ) ax.annotate( f"crossover {speeds[crossing]:.0f} km/h", xy=(speeds[crossing], rolling[crossing]), xytext=(6, -16), textcoords=_OFFSET_POINTS, fontsize=9, color=color, ) ax.set_title( "CNOSSOS-EU Single-Vehicle Sound Power against Speed (reference conditions)", pad=12, ) ax.set_xlabel("Speed $v$ [km/h]") ax.set_ylabel(r"A-weighted sound power $L_{W\!,\mathrm{A}}$ [dB(A) re 1 pW]") ax.set_xlim(20.0, 130.0) ax.grid(color=COLOR_GRID, linestyle="--", alpha=0.5, zorder=0) ax.set_axisbelow(True) ax.legend(loc="lower right", fontsize=9, ncol=2) plt.tight_layout() save_figure(output_dir, "cnossos_road_speed_law.png") plt.close() def _statistical_pass_by_site() -> StatisticalPassByResult: """The medium-speed site the road-surface guide measures, seeded. The same pass-bys the guide's code block draws: per category a count, a mean speed, a spread of ``lg v`` and the line and scatter they are drawn around, so the figure and the printed numbers are one measurement. """ from phonometry import environment rng = np.random.default_rng(11819) site = { "1": (120, 88.0, 0.055, 16.6, 32.6, 1.4), "2a": (40, 76.0, 0.050, 46.5, 18.8, 2.0), "2b": (50, 74.0, 0.045, 34.5, 26.7, 2.0), } categories: list[str] = [] speeds: list[float] = [] levels: list[float] = [] for category, (n, mean_kmh, spread, a, b, scatter) in site.items(): lg_v = np.log10(mean_kmh) + spread * rng.standard_normal(n) categories += [category] * n speeds += (10.0**lg_v).tolist() levels += (a + b * lg_v + scatter * rng.standard_normal(n)).tolist() return environment.statistical_pass_by( categories, speeds, levels, road_speed_category="medium", reference_levels=environment.SPB_NORMALIZED_REFERENCE_LEVELS, ) def generate_statistical_pass_by(output_dir: str) -> None: """ISO 11819-1: the three clouds of a site, their lines and the index.""" print("Generating statistical_pass_by...") result = _statistical_pass_by_site() _fig, ax = plt.subplots(figsize=(10, 6.2)) result.plot(ax=ax, language=_LANG) plt.tight_layout() save_figure(output_dir, "statistical_pass_by.svg") plt.close() def generate_pass_by_regression(output_dir: str) -> None: """ISO 11819-1: one category's line, the 9.3 window and L_veh.""" print("Generating pass_by_regression...") result = _statistical_pass_by_site() _fig, ax = plt.subplots(figsize=(10, 6.2)) result.regressions["1"].plot(ax=ax, language=_LANG) plt.tight_layout() save_figure(output_dir, "pass_by_regression.svg") plt.close() def generate_ground_effect_spherical(output_dir: str) -> None: """Spherical-wave ground effect (Weyl-Van der Pol) for four ground types.""" print("Generating ground_effect_spherical.png...") import warnings as _warnings from phonometry import environment freqs = np.geomspace(50.0, 4000.0, 400) # Effective flow resistivities (kPa s/m2 -> Pa s/m2) after Attenborough Ch. 2 # / Salomons Sec. 3.1: fresh snow, forest floor, grassland and a near-hard # surface (asphalt / compacted soil). grounds = [ ("Fresh snow (10 kPa·s·m⁻²)", 10e3, COLOR_TERTIARY), ("Forest floor (50 kPa·s·m⁻²)", 50e3, "#9467bd"), ("Grassland (200 kPa·s·m⁻²)", 200e3, COLOR_PRIMARY), ("Asphalt (20 000 kPa·s·m⁻²)", 20000e3, COLOR_SECONDARY), ] _fig, ax = plt.subplots(figsize=(11, 6.4)) with _warnings.catch_warnings(): _warnings.simplefilter("ignore") for label, sigma, color in grounds: res = environment.ground_effect( freqs, 1.0, 1.5, 50.0, flow_resistivity_pa_s_m2=sigma ) ax.plot( freqs, res.excess_attenuation, color=color, linewidth=1.8, label=label, zorder=3, ) ax.axhline( 6.0, color=COLOR_FG, linestyle=":", linewidth=1.0, alpha=0.7, label="Hard-ground limit (+6 dB)", ) ax.axhline(0.0, color=COLOR_FG, linewidth=0.8, alpha=0.6) ax.set_xscale("log") ax.set_title("Spherical-Wave Ground Effect (Weyl-Van der Pol)", pad=12) ax.set_xlabel("Frequency [Hz]") ax.set_ylabel("Level re free field [dB]") ax.set_xlim(50.0, 4000.0) ax.set_ylim(-20.0, 8.0) format_frequency_axis(ax, 50.0, 4000.0, language=_LANG) ax.grid(which="both", color=COLOR_GRID, linestyle="--", alpha=0.5, zorder=0) ax.set_axisbelow(True) ax.legend(loc="lower left", fontsize=9) plt.tight_layout() save_figure(output_dir, "ground_effect_spherical.png") plt.close() def generate_atmospheric_refraction(output_dir: str) -> None: """Atmospheric refraction: curved rays and the GFPE shadow-zone field.""" print("Generating atmospheric_refraction.png...") import warnings as _warnings from phonometry import environment # Upward-refracting surface layer (b = -1 m/s) over grassland: rays curve # up and leave an acoustic shadow near the ground (Salomons Sec. 4.4/4.6). c0, b = 340.0, -1.0 prof = environment.log_linear_sound_speed_profile( b, ground_speed_of_sound=c0, max_height_m=60.0 ) zs = 2.0 fig, axes = plt.subplots(2, 1, figsize=(11, 8.2), sharex=True) # (a) Ray fan from a near-ground source. rays = environment.atmospheric_ray_paths( prof, source_height_m=zs, launch_angles_deg=np.linspace(-8.0, 8.0, 17), max_range=600.0, n_steps=3000, ) for i in range(rays.heights_m.shape[0]): axes[0].plot( rays.ranges[i], rays.heights_m[i], color=COLOR_PRIMARY, lw=0.8, alpha=0.7, zorder=2, ) axes[0].plot( [0.0], [zs], "o", color=COLOR_SECONDARY, ms=7, zorder=4, label="Source" ) # The linear-gradient shadow distance (grazing ray at hr = zs) as a guide. grad = (prof.speed_at(10.0) - c0) / 10.0 x_sh = environment.shadow_zone_distance( float(grad), zs, zs, ground_speed_of_sound=c0 ) axes[0].axvline( x_sh, color=COLOR_SECONDARY, ls="--", lw=1.2, zorder=3, label="Shadow-zone boundary", ) axes[0].set_ylabel("Height [m]") axes[0].set_ylim(0.0, 40.0) axes[0].set_title("Sound rays (upward refraction)", pad=8) axes[0].grid(which="both", color=COLOR_GRID, ls="--", alpha=0.5, zorder=0) axes[0].set_axisbelow(True) axes[0].legend(loc="upper right", fontsize=9) # (b) GFPE relative-level field over the same atmosphere and ground. with _warnings.catch_warnings(): _warnings.simplefilter("ignore") pe = environment.atmospheric_parabolic_equation( 400.0, prof, source_height_m=zs, flow_resistivity_pa_s_m2=200e3, max_range=600.0, max_height_m=40.0, ) dl = np.where(np.isfinite(pe.relative_level), pe.relative_level, np.nan) img = axes[1].imshow( dl, cmap="RdBu_r", vmin=-30.0, vmax=6.0, aspect="auto", origin="lower", interpolation="bilinear", extent=( float(pe.ranges[0]), float(pe.ranges[-1]), float(pe.heights_m[0]), float(pe.heights_m[-1]), ), zorder=1, ) axes[1].axvline(x_sh, color=COLOR_FG, ls="--", lw=1.2, alpha=0.8, zorder=2) axes[1].plot([0.0], [zs], "o", color="k", ms=6, zorder=3) axes[1].set_ylabel("Height [m]") axes[1].set_xlabel("Range [m]") axes[1].set_ylim(0.0, 40.0) axes[1].set_title("GFPE relative sound level", pad=8) fig.colorbar(img, ax=axes[1], label="Level re free field [dB]", pad=0.01) fig.suptitle( "Atmospheric Refraction: Ray Bending and the Acoustic Shadow", fontsize=13 ) plt.tight_layout() save_figure(output_dir, "atmospheric_refraction.png") plt.close() def generate_barrier_geometry(output_dir: str) -> None: """To-scale section of the barrier of the insertion-loss figure. The 4 m screen 50 m from a 1 m source with the receiver 1,5 m high at 100 m: direct and diffracted paths and the path-length difference that drives the Fresnel number. One concept: the geometry the insertion-loss methods share. """ print("Generating barrier_geometry...") from phonometry import environment _fig, ax = plt.subplots(figsize=(10, 5.4)) environment.plot_barrier_geometry( ax=ax, source_height_m=1.0, barrier_distance=50.0, barrier_height_m=4.0, receiver_distance=100.0, receiver_height_m=1.5, language=_LANG, ) plt.tight_layout() save_figure(output_dir, "barrier_geometry.svg") plt.close() def generate_impulse_prominence(output_dir: str) -> None: """NT ACOU 112: predicted prominence and the LAeq adjustment.""" print("Generating impulse_prominence.png...") from phonometry import environment from phonometry.environment.assessment.impulsive_sound import ( _ADJUSTMENT_THRESHOLD, ) _fig, (ax_p, ax_k) = plt.subplots(1, 2, figsize=(12.5, 5.4)) # --- Left: P vs onset rate for three level differences (Formula 1). --- orate = np.logspace(1, 4, 200) # 10 to 10000 dB/s # Distinct hues (not COLOR_GRID, which is near-invisible on a light ground). for ld, colour in ( (5.0, COLOR_TERTIARY), (15.0, COLOR_PRIMARY), (30.0, COLOR_SECONDARY), ): ax_p.plot( orate, environment.predicted_prominence(orate, np.full_like(orate, ld)), color=colour, label=rf"$\mathrm{{LD}}$ = {ld:g} dB", ) ax_p.set_xscale("log") ax_p.set_xlabel("Onset rate [dB/s]") ax_p.set_ylabel("Predicted prominence $P$") ax_p.set_title( r"$P = 3\,\log_{10}(\mathrm{OR}) + 2\,\log_{10}(\mathrm{LD})$", pad=10 ) ax_p.grid(which="both", color=COLOR_GRID, linestyle="-", alpha=0.4) ax_p.set_axisbelow(True) ax_p.legend(loc="upper left") # --- Right: the adjustment KI(P) with example impulses. --- result = environment.impulse_prominence([1200.0, 300.0, 60.0], [32.0, 18.0, 11.0]) grid = np.linspace(0.0, 16.0, 200) ax_k.plot( grid, environment.impulse_adjustment(grid), color=COLOR_PRIMARY, label=r"$K_{\mathrm{I}} = 1.8\,(P-5)$", ) ax_k.axvline( _ADJUSTMENT_THRESHOLD, color="#7f7f7f", linestyle=":", label=f"threshold $P = {_ADJUSTMENT_THRESHOLD:g}$", ) ax_k.scatter( result.per_impulse, environment.impulse_adjustment(result.per_impulse), color="#aec7e8", zorder=3, label="Impulses", ) ax_k.scatter( [result.prominence], [result.adjustment], color=COLOR_SECONDARY, marker="*", s=140, zorder=4, label=rf"Governing $K_{{\mathrm{{I}}}}$ = {result.adjustment:.1f} dB", ) ax_k.set_xlabel("Predicted prominence $P$") ax_k.set_ylabel(r"Adjustment $K_{\mathrm{I}}$ [dB]") ax_k.set_title(r"Adjustment to $L_{\mathrm{Aeq}}$", pad=10) ax_k.set_ylim(bottom=0.0) ax_k.grid(color=COLOR_GRID, linestyle="-", alpha=0.4) ax_k.set_axisbelow(True) ax_k.legend(loc="upper left") plt.tight_layout() save_figure(output_dir, "impulse_prominence.png") plt.close() def _tow_launcher_distribution() -> "SELDistribution": """ISO 13474 Annex A: the TOW launcher heard at 3 020 m (Table A.3). The 27 A-weighted single-event levels and their 07:00 to 19:00 probabilities, formed from the day and night columns at the 80 % and 20 % the annex states. """ from phonometry import environment levels = [30.5, 31.2, 31.3, 36.1, 38.3, 38.8, 39.2, 30.8, 31.8, 31.8, 33.7, 40.2, 41.0, 41.6, 42.2, 42.4, 42.7, 43.1, 28.4, 30.8, 32.2, 42.3, 43.6, 44.5, 45.2, 45.5, 46.1] # fmt: skip day = [0.0360, 0.0053, 0.0003, 0.0731, 0.0951, 0.0634, 0.0, 0.2037, 0.1087, 0.0184, 0.0279, 0.0001, 0.0, 0.0549, 0.0482, 0.0209, 0.0039, 0.0003, 0.0, 0.0356, 0.2042, 0.0001, 0.0, 0.0, 0.0, 0.0, 0.0] # fmt: skip night = [0.0, 0.0, 0.0, 0.0664, 0.0966, 0.0962, 0.0, 0.1151, 0.0295, 0.0, 0.0268, 0.0084, 0.0, 0.0665, 0.0445, 0.0172, 0.0033, 0.0003, 0.0069, 0.0798, 0.2310, 0.0215, 0.0260, 0.0263, 0.0194, 0.0153, 0.0030] # fmt: skip period = 0.8 * np.asarray(day) + 0.2 * np.asarray(night) return environment.sel_distribution(levels, period, sigma_db=5.0, n_subclasses=10) def generate_sel_distribution_density(output_dir: str) -> None: """ISO 13474: the class density and the density spread for turbulence.""" print("Generating sel_distribution_density...") dist = _tow_launcher_distribution() _fig, (ax_classes, ax_density) = plt.subplots(1, 2, figsize=(13.5, 5.4)) dist.plot(ax_classes, view="classes", language=_LANG) dist.plot(ax_density, view="density", language=_LANG) plt.tight_layout() save_figure(output_dir, "sel_distribution_density.svg") plt.close() def generate_sel_distribution_exceedance(output_dir: str) -> None: """ISO 13474: the exceedance curve with the Figure A.3 levels marked.""" print("Generating sel_distribution_exceedance...") dist = _tow_launcher_distribution() _fig, ax = plt.subplots(figsize=(10, 6)) dist.plot(ax, view="exceedance", language=_LANG) plt.tight_layout() save_figure(output_dir, "sel_distribution_exceedance.svg") plt.close() #: Eleven London sites of the International Soundscape Database v1.0 (Mitchell, #: Oberman, Aletta et al., Zenodo, DOI 10.5281/zenodo.10672568, CC BY 4.0), #: surveyed almost entirely with the English questionnaire of ISO/TS 12913-2 #: Method A (ten of the answers, at four of the sites, were given on the #: Spanish version of the database's survey, and are counted as well): the #: median of the eight perceived affective quality answers per site (pleasant, #: chaotic, vibrant, uneventful, calm, annoying, eventful, monotonous) and the #: median LAeq of the site's recordings, in dB. Derived for the guide; the same #: values are in ``tests/reference_data/soundscape.py``. _LONDON_SITES: tuple[tuple[str, tuple[float, ...], float], ...] = ( ("Camden Town", (3, 4, 4, 2, 2, 3, 4, 3), 69.96), ("Euston Tap", (2, 4, 3, 3, 2, 3, 3, 3), 69.45), ("Marchmont Garden", (4, 2, 3, 3, 4, 2, 3, 2), 55.14), ("Pancras Lock", (4, 3, 3, 2, 4, 2, 3, 2), 59.02), ("Regent's Park Fields", (5, 2, 3, 3, 4, 1, 3, 2), 53.12), ("Regent's Park Japan", (5, 1, 4, 3, 5, 1, 3, 2), 59.74), ("Russell Square", (4, 2, 4, 2, 4, 1, 3, 2), 66.12), ("St Paul's Cross", (4, 2.5, 4, 2, 4, 2, 3, 2), 61.83), ("St Paul's Row", (4, 3, 4, 2, 3, 2, 3, 3), 63.34), ("Tate Modern", (4, 3, 4, 2, 4, 2, 4, 2), 63.00), ("Torrington Square", (3, 4, 4, 3, 2, 3, 3, 2), 63.51), ) def generate_soundscape_pleasantness_eventfulness(output_dir: str) -> None: """ISO/TS 12913-3: eleven London sites on Figure A.1, and P against LAeq.""" print("Generating soundscape_pleasantness_eventfulness...") from phonometry import environment medians = np.array([row[1] for row in _LONDON_SITES], dtype=float) laeq = np.array([row[2] for row in _LONDON_SITES]) sites = [row[0] for row in _LONDON_SITES] result = environment.pleasantness_eventfulness(medians, sites=sites) correlation = environment.spearman_rank_correlation(result.pleasantness, laeq) _fig, (ax_model, ax_rank) = plt.subplots(1, 2, figsize=(14.0, 6.6)) result.plot(ax_model, language=_LANG) correlation.plot(ax_rank, language=_LANG) # The renderer names its axes x and y; here they are the two things the # sites were ranked by, and the save-time pass writes them in Spanish. ax_rank.set_xlabel(r"Rank of the site pleasantness $P$") ax_rank.set_ylabel(r"Rank of the site $L_\mathrm{Aeq}$") plt.tight_layout() save_figure(output_dir, "soundscape_pleasantness_eventfulness.svg") plt.close() def _binaural_street() -> NDArray[np.float64]: """Eight seconds at a kerb: steady noise, one vehicle passing left to right. The pass-by rises by about 12 dB in the middle of the record and reaches the left ear first and louder; the right ear hears the same event a little later and 3 dB down. Calibrated in pascals, 48 kHz. """ fs = 48_000 rng = np.random.default_rng(12913) n = 8 * fs t = np.arange(n) / fs background = 0.02 * rng.standard_normal(n) swell = np.exp(-0.5 * ((t - 4.0) / 0.9) ** 2) vehicle = 0.08 * rng.standard_normal(n) left = background + swell * vehicle lag = int(0.3 * fs) right = 0.9 * background + 10.0 ** (-3.0 / 20.0) * np.roll(swell, lag) * vehicle return np.vstack([left, right]) def generate_soundscape_binaural_indicators(output_dir: str) -> None: """ISO/TS 12913-3 Table D.1: the levels and the loudness at both ears.""" import warnings print("Generating soundscape_binaural_indicators...") from phonometry import environment with warnings.catch_warnings(): warnings.simplefilter("ignore", environment.SoundscapeWarning) result = environment.binaural_indicators( _binaural_street(), 48_000, parameters=("sound_pressure_level", "loudness") ) _fig, (ax_levels, ax_loudness) = plt.subplots(1, 2, figsize=(14.0, 5.8)) result.plot(ax_levels, parameter="sound_pressure_level", language=_LANG) result.plot(ax_loudness, parameter="loudness", language=_LANG) plt.tight_layout() save_figure(output_dir, "soundscape_binaural_indicators.svg") plt.close() def generate_tonal_audibility(output_dir: str) -> None: """ISO 1996-2: tonal adjustment Kt(ΔLta) with the Annex C.5 examples.""" print("Generating tonal_audibility...") from phonometry import environment # The four ISO 1996-2:2007 Annex C.5 worked examples: (Lpt, Lpn, fc). examples = [ (46.7, 37.3, 4000.0), (54.1, 45.2, 430.0), (53.6, 45.5, 755.0), (54.6, 45.5, 308.0), ] assessed = [ environment.assess_tonal_audibility(lpt, lpn, fc) for lpt, lpn, fc in examples ] # A synthetic mid-range tone to exercise the sloped branch. mid = environment.assess_tonal_audibility(50.0, 44.0, 500.0) grid = np.linspace(0.0, 15.0, 300) curve = np.array([environment.tonal_adjustment(d) for d in grid]) _fig, ax = plt.subplots(figsize=(10, 6.2)) ax.plot( grid, curve, "-", color=COLOR_PRIMARY, linewidth=2.4, zorder=5, label=r"$K_{\mathrm{t}}(\Delta L_{\mathrm{ta}})$ (Formulae C.4-C.6)", ) for x in (4.0, 10.0): ax.axvline(x, color=COLOR_GRID, linestyle=":", alpha=0.8, zorder=1) ax.scatter( [a.audibility for a in assessed], [a.adjustment for a in assessed], color=COLOR_SECONDARY, marker="o", s=70, zorder=6, label="Annex C.5 examples", ) ax.scatter( [mid.audibility], [mid.adjustment], color=COLOR_TERTIARY, marker="*", s=150, zorder=7, label="mid-range tone", ) ax.set_xlabel(r"Tonal audibility $\Delta L_{\mathrm{ta}}$ [dB]") ax.set_ylabel(r"Tonal adjustment $K_{\mathrm{t}}$ [dB]") ax.set_ylim(-0.3, 6.6) ax.set_title("ISO 1996-2 Tonal Adjustment", pad=12) ax.grid(color=COLOR_GRID, linestyle="--", alpha=0.5, zorder=0) ax.set_axisbelow(True) ax.legend(loc="lower right", fontsize=9) info = [ r"$K_{\mathrm{t}} = 0$ ($\Delta L_{\mathrm{ta}} < 4$)", ( r"$K_{\mathrm{t}} = \Delta L_{\mathrm{ta}} - 4$ " r"($4 \leq \Delta L_{\mathrm{ta}} \leq 10$)" ), r"$K_{\mathrm{t}} = 6$ ($\Delta L_{\mathrm{ta}} > 10$)", ] ax.text( 0.015, 0.97, "\n".join(info), transform=ax.transAxes, va="top", ha="left", fontsize=10, color=COLOR_FG, bbox={ "boxstyle": "round,pad=0.5", "facecolor": COLOR_PANEL, "edgecolor": COLOR_GRID, }, ) plt.tight_layout() save_figure(output_dir, "tonal_audibility.png") plt.close() def generate_impulsive_sound_onsets(output_dir: str) -> None: """ISO/PAS 1996-3 LpAF history with the detected impulse onsets.""" print("Generating impulsive_sound_onsets...") import warnings as _warnings from phonometry import environment # Three hammer strikes over a 55 dB(A) background, 6 s at 48 kHz: the # objective chain samples LpAF, detects the onsets and rates the source. fs = 48000 rng = np.random.default_rng(7) t = np.arange(int(6.0 * fs)) / fs background = rng.standard_normal(t.size) background *= 2e-5 * 10 ** (55 / 20) / np.sqrt(np.mean(background**2)) signal = background.copy() for onset_time in (1.0, 2.6, 4.2): decay = np.exp(-(t - onset_time) / 0.08) * (t >= onset_time) strike = decay * rng.standard_normal(t.size) window = (t >= onset_time) & (t < onset_time + 0.1) strike *= 2e-5 * 10 ** (95 / 20) / np.sqrt(np.mean(strike[window] ** 2)) signal += strike with _warnings.catch_warnings(): # The synthetic interval is shorter than the assessment period. _warnings.simplefilter("ignore") res = environment.impulsive_sound_adjustment(signal, fs) _fig, ax = plt.subplots(figsize=(10, 6)) res.plot(ax=ax, language=_LANG) # The level-difference readout is anchored on the governing onset, which # is where the history is steepest: the curve, the fitted onset line and # the double-headed arrow all cross the letters. Back it with the # documentation chip. for label in ax.texts: if label.get_text().strip(): label.set_zorder(6) label.set_bbox( { "boxstyle": "round,pad=0.3", "facecolor": COLOR_PANEL, "edgecolor": COLOR_GRID, } ) plt.tight_layout() save_figure(output_dir, "impulsive_sound_onsets.svg") plt.close() def generate_atmospheric_sound_speed_profiles(output_dir: str) -> None: """Log-linear effective sound-speed profiles: downward vs upward refraction.""" print("Generating atmospheric_sound_speed_profiles...") from phonometry import environment down = environment.log_linear_sound_speed_profile( +1.0, ground_speed_of_sound=340.0, max_height_m=60.0 ) up = environment.log_linear_sound_speed_profile( -1.0, ground_speed_of_sound=340.0, max_height_m=60.0 ) _fig, ax = plt.subplots(figsize=(7.0, 7.5)) ax.plot( down.speeds_of_sound, down.heights_m, color=COLOR_PRIMARY, linewidth=2.0, label="Downward refraction ($b$ = +1 m/s)", zorder=3, ) ax.plot( up.speeds_of_sound, up.heights_m, color=COLOR_SECONDARY, linewidth=2.0, label="Upward refraction ($b$ = −1 m/s)", zorder=3, ) ax.axvline(340.0, color=COLOR_FG, linestyle=":", linewidth=0.9, alpha=0.6) ax.set_xlabel("Effective sound speed [m/s]") ax.set_ylabel("Height [m]") ax.set_ylim(0.0, 60.0) ax.set_title("Effective Sound-Speed Profiles (Salomons Eq. 4.5)", pad=12) ax.grid(color=COLOR_GRID, linestyle="--", alpha=0.5) ax.set_axisbelow(True) ax.legend(loc="upper center", fontsize=9) plt.tight_layout() save_figure(output_dir, "atmospheric_sound_speed_profiles.svg") plt.close() def generate_atmospheric_ray_fan(output_dir: str) -> None: """Downward-refraction ray fan: every ray returns to the ground and bounces.""" print("Generating atmospheric_ray_fan...") from phonometry import environment profile = environment.log_linear_sound_speed_profile( +1.0, ground_speed_of_sound=340.0, max_height_m=60.0 ) zs = 2.0 rays = environment.atmospheric_ray_paths( profile, source_height_m=zs, launch_angles_deg=np.linspace(-8.0, 8.0, 17), max_range=600.0, n_steps=600, ) _fig, ax = plt.subplots(figsize=(11.0, 5.6)) for i in range(rays.heights_m.shape[0]): ax.plot( rays.ranges[i], rays.heights_m[i], color=COLOR_PRIMARY, lw=0.8, alpha=0.7, zorder=2, ) ax.plot([0.0], [zs], "o", color=COLOR_SECONDARY, ms=7, zorder=4, label="Source") ax.axhline(0.0, color=COLOR_FG, lw=1.0, alpha=0.7) ax.set_xlabel("Range [m]") ax.set_ylabel("Height [m]") ax.set_xlim(0.0, 600.0) ax.set_ylim(0.0, 40.0) ax.set_title("Sound Rays under Downward Refraction ($b$ = +1 m/s)", pad=12) ax.text( 0.985, 0.94, "shallow rays are bent back to the ground\nand bounce on down-range", transform=ax.transAxes, va="top", ha="right", fontsize=9, color=COLOR_FG, zorder=6, bbox={ "boxstyle": "round,pad=0.5", "facecolor": COLOR_PANEL, "edgecolor": COLOR_GRID, }, ) ax.grid(color=COLOR_GRID, linestyle="--", alpha=0.5) ax.set_axisbelow(True) ax.legend(loc="upper left", fontsize=9) plt.tight_layout() save_figure(output_dir, "atmospheric_ray_fan.svg") plt.close() def generate_atmospheric_pe_range(output_dir: str) -> None: """GFPE relative level vs range at 2 m for three refraction conditions.""" print("Generating atmospheric_pe_range...") import warnings as _warnings from phonometry import environment c0, zs, zr = 340.0, 2.0, 2.0 cases = [ ( environment.log_linear_sound_speed_profile( +1.0, ground_speed_of_sound=c0, max_height_m=60.0 ), COLOR_PRIMARY, "-", "Downward ($b$ = +1 m/s)", ), ( environment.linear_sound_speed_profile( 0.0, ground_speed_of_sound=c0, max_height_m=60.0 ), COLOR_FG, "--", "Homogeneous ($b$ = 0)", ), ( environment.log_linear_sound_speed_profile( -1.0, ground_speed_of_sound=c0, max_height_m=60.0 ), COLOR_SECONDARY, "-", "Upward ($b$ = −1 m/s)", ), ] _fig, ax = plt.subplots(figsize=(11.0, 6.2)) with _warnings.catch_warnings(): _warnings.simplefilter("ignore") for profile, color, ls, label in cases: pe = environment.atmospheric_parabolic_equation( 400.0, profile, source_height_m=zs, flow_resistivity_pa_s_m2=200e3, max_range=600.0, max_height_m=40.0, ) ax.plot( pe.ranges, pe.level_at_height(zr), color=color, ls=ls, lw=1.6, label=label, zorder=3, ) # The closed-form shadow boundary of the equivalent linear upward gradient # (the 10 m mean gradient of the log profile), as in the page-top figure. up_prof = cases[2][0] grad = (up_prof.speed_at(10.0) - c0) / 10.0 x_sh = environment.shadow_zone_distance( float(grad), zs, zr, ground_speed_of_sound=c0 ) ax.axvline( x_sh, color=COLOR_SECONDARY, ls=":", lw=1.2, zorder=2, label="Shadow-zone boundary", ) ax.axhline(0.0, color=COLOR_FG, lw=0.8, alpha=0.6) ax.set_xlabel("Range [m]") ax.set_ylabel("Level re free field [dB]") ax.set_xlim(0.0, 600.0) ax.set_ylim(-40.0, 10.0) ax.set_title("GFPE Relative Level at the Receiver Height (400 Hz, 2 m)", pad=12) ax.grid(color=COLOR_GRID, linestyle="--", alpha=0.5) ax.set_axisbelow(True) ax.legend(loc="lower left", fontsize=9) plt.tight_layout() save_figure(output_dir, "atmospheric_pe_range.svg") plt.close() def generate_barrier_insertion_loss_methods(output_dir: str) -> None: """Wave-theoretic barrier insertion loss: Kurze-Anderson, exact, exact + ground.""" print("Generating barrier_insertion_loss_methods...") import warnings as _warnings from phonometry import environment # A 4 m barrier 50 m from a 1 m source, receiver 1.5 m high at 100 m # (the geometry of the ground-barriers guide snippets). freqs = np.geomspace(50.0, 5000.0, 240) with _warnings.catch_warnings(): _warnings.simplefilter("ignore") il_ka = environment.barrier_insertion_loss( freqs, 1.0, 50.0, 4.0, 100.0, 1.5, method="kurze_anderson" ) il_ex = environment.barrier_insertion_loss( freqs, 1.0, 50.0, 4.0, 100.0, 1.5, method="exact" ) il_gr = environment.barrier_insertion_loss( freqs, 1.0, 50.0, 4.0, 100.0, 1.5, method="exact", ground_flow_resistivity_pa_s_m2=2e5, ) _fig, ax = plt.subplots(figsize=(11.0, 6.4)) ax.plot( freqs, il_ka.insertion_loss, color=COLOR_TERTIARY, lw=1.8, ls="--", label="Kurze-Anderson (thin screen)", zorder=3, ) ax.plot( freqs, il_ex.insertion_loss, color=COLOR_PRIMARY, lw=1.8, label="Exact rigid half-plane", zorder=3, ) ax.plot( freqs, il_gr.insertion_loss, color=COLOR_SECONDARY, lw=1.4, alpha=0.9, label="Exact + coherent ground (four paths)", zorder=2, ) ax.axhline( 5.0, color=COLOR_FG, ls=":", lw=1.0, alpha=0.7, label="Kurze-Anderson grazing limit (5 dB)", ) ax.set_xscale("log") ax.set_xlabel("Frequency [Hz]") ax.set_ylabel("Insertion loss [dB]") ax.set_xlim(50.0, 5000.0) format_frequency_axis(ax, 50.0, 5000.0, language=_LANG) ax.set_title("Wave-Theoretic Barrier Insertion Loss", pad=12) ax.grid(which="both", color=COLOR_GRID, linestyle="--", alpha=0.5) ax.set_axisbelow(True) ax.legend(loc="upper left", fontsize=9) plt.tight_layout() save_figure(output_dir, "barrier_insertion_loss_methods.svg") def generate_rd1367_activity_assessment(output_dir: str) -> None: """RD 1367/2007 activity assessment against the Annex III Table B1 limits. The worked case of Avilés López & Perera Martín, Manual de acústica ambiental y arquitectónica, Ejemplos 3.1 to 3.3: an activity on residential land whose day period splits into 2 h shut down, 6 h with a noisy machine (LKeq,Ti = 59 dB) and 4 h with the remaining sources (54 dB), giving LKeq,d = 57 dB and, over 303 operating days, LK,d = 56 dB. Against the 55 dB limit of area type a the phase (+5 dB) and daily (+3 dB) criteria are met but the annual one is not. """ print("Generating rd1367_activity_assessment.png...") from phonometry import environment day = [ environment.NoisePhase(duration_hours=2.0, laeq=0.0, label="closed"), environment.NoisePhase(duration_hours=6.0, laeq=50.0, kt=6.0, kf=3.0), environment.NoisePhase(duration_hours=4.0, laeq=48.0, kt=3.0, kf=3.0), ] evening = [ environment.NoisePhase(duration_hours=2.0, laeq=48.0, kt=3.0, kf=3.0), environment.NoisePhase(duration_hours=2.0, laeq=0.0), ] verdict = environment.assess_activity( {"day": day, "evening": evening}, environment.activity_limits("a"), operating_days=303, ) _, ax = plt.subplots(figsize=(10, 6)) # The result's own .plot() draws the three Article 25.1 b indices per # period with their own allowances marked on each group. verdict.plot(ax=ax, language=_LANG) ax.set_ylim(0, 72) save_figure(output_dir, "rd1367_activity_assessment.png") plt.close() def _cnossos_rail_scene() -> tuple[Any, Any]: """A four-axle disc-braked coach on a normally maintained ballasted track. The vehicle is the 920 mm wheel of Table G-3b at the 50 kN wheel load of Table G-2, the track a concrete mono-block sleeper on a medium-stiffness rail pad with one joint per 100 m, which is the default Annex II prescribes for jointed track. """ from phonometry import environment stock = environment.RollingStock( n_axles=4, wheel_roughness=environment.wheel_roughness(environment.BrakeType.NON_TREAD), contact_filter=environment.contact_filter( environment.ContactFilter.LOAD_50_DIAMETER_920 ), wheel_transfer=environment.wheel_transfer(environment.WheelDiameter.MM_920), traction=environment.traction_sound_power( environment.TractionVehicle.ELECTRIC_MULTIPLE_UNIT ), aerodynamic=environment.aerodynamic_sound_power(), ) track = environment.RailwayTrack( rail_roughness=environment.rail_roughness( environment.RailRoughnessClass.NORMAL ), track_transfer=environment.track_transfer( environment.TrackTransferClass.MONOBLOCK_MEDIUM ), impact_roughness=environment.impact_roughness_single(), ) return stock, track def generate_cnossos_rail_emission(output_dir: str) -> None: """CNOSSOS-EU railway source-line power at the two equivalent heights.""" print("Generating cnossos_rail_emission.png...") from phonometry import environment stock, track = _cnossos_rail_scene() bands = np.array([63.0, 125.0, 250.0, 500.0, 1000.0, 2000.0, 4000.0, 8000.0]) # 96 coaches per hour at 160 km/h: eight eight-car trains an hour on a # conventional main line, seen broadside and slightly from above. result = environment.railway_source_power( environment.RailwayVehicle(stock=stock, flow_rate=96.0, speed_kmh=160.0), track, phi=90.0, psi=10.0, ) x = np.arange(len(bands)) _fig, ax = plt.subplots(figsize=(11, 6.4)) ax.bar( x, result.total_line_power, color=COLOR_MUTED, edgecolor=COLOR_FG, linewidth=0.6, label="Both source heights", zorder=2, ) for row, color, marker, label in zip( result.line_power, (COLOR_PRIMARY, COLOR_SECONDARY), ("o", "s"), ( "Source A, 0,5 m (rolling, impact, traction)", "Source B, 4,0 m (traction, aerodynamic)", ), strict=True, ): ax.plot( x, row, color=color, marker=marker, linewidth=1.8, markersize=6, markerfacecolor="white", markeredgewidth=1.3, zorder=5, label=label, ) ax.set_title( "CNOSSOS-EU Railway Source Line Power (96 coaches/h at 160 km/h)", pad=12, ) ax.set_xlabel("Octave-band centre frequency [Hz]") ax.set_ylabel(r"Line power $L^{\prime}_{W,\mathrm{eq,line}}$ [dB re 1 pW/m]") ax.set_xticks(x) ax.set_xticklabels([f"{b:g}" for b in bands]) ax.set_ylim(30.0, 95.0) ax.grid(axis="y", color=COLOR_GRID, linestyle="--", alpha=0.5, zorder=0) ax.set_axisbelow(True) ax.legend(loc="lower left", fontsize=9) plt.tight_layout() save_figure(output_dir, "cnossos_rail_emission.png") plt.close() def generate_cnossos_rail_roughness_shift(output_dir: str) -> None: """The roughness spectrum sliding along the frequency axis with speed.""" print("Generating cnossos_rail_roughness_shift.png...") from phonometry import environment freqs = np.asarray(environment.RAILWAY_THIRD_OCTAVE_BANDS_HZ) rail = environment.rail_roughness(environment.RailRoughnessClass.NORMAL) wheel = environment.wheel_roughness(environment.BrakeType.NON_TREAD) filt = environment.contact_filter(environment.ContactFilter.LOAD_50_DIAMETER_920) _fig, ax = plt.subplots(figsize=(11, 6.4)) for speed, color, marker in ( (60.0, COLOR_PRIMARY, "o"), (160.0, COLOR_TERTIARY, "s"), (300.0, COLOR_SECONDARY, "D"), ): total = environment.total_effective_roughness( environment.roughness_to_frequency( rail.levels, wavelengths_mm=rail.wavelengths_mm, speed_kmh=speed ), environment.roughness_to_frequency( wheel.levels, wavelengths_mm=wheel.wavelengths_mm, speed_kmh=speed ), environment.roughness_to_frequency( filt.levels, wavelengths_mm=filt.wavelengths_mm, speed_kmh=speed ), ) ax.semilogx( freqs, total, color=color, marker=marker, linewidth=1.8, markersize=5, markerfacecolor="white", markeredgewidth=1.2, label=f"$v$ = {speed:g} km/h", zorder=4, ) ax.axhline(0.0, color=COLOR_MUTED, linewidth=0.9, zorder=1) ax.set_title( "CNOSSOS-EU Total Effective Roughness against Speed " r"($f = v/\lambda$, $\lambda$ in the wavelength domain)", pad=12, ) ax.set_xlabel("1/3-octave band centre frequency [Hz]") ax.set_ylabel(r"Total effective roughness $L_{\mathrm{R,TOT}}$ [dB re 1 μm]") ax.set_xlim(50.0, 10000.0) format_frequency_axis(ax, 50.0, 10000.0, language=_LANG) ax.grid(which="both", color=COLOR_GRID, linestyle="--", alpha=0.5, zorder=0) ax.set_axisbelow(True) ax.legend(loc="upper right", fontsize=10) plt.tight_layout() save_figure(output_dir, "cnossos_rail_roughness_shift.png") plt.close() def generate_outdoor_level_cascade(output_dir: str) -> None: """Where the source power goes, band by band (ISO 9613-2 book-keeping).""" print("Generating outdoor_level_cascade.svg...") from phonometry import environment bands = np.array([63.0, 125.0, 250.0, 500.0, 1000.0, 2000.0, 4000.0, 8000.0]) barrier = environment.Barrier(source_to_edge=101.0, edge_to_receiver=101.0) att = environment.outdoor_propagation_attenuation( 200.0, 1.5, 1.5, frequencies=bands, ground_source=1.0, ground_middle=1.0, ground_receiver=1.0, barrier=barrier, temperature_c=15.0, relative_humidity_percent=70.0, ) lw = np.full(bands.size, 95.0) x = np.arange(bands.size) level = lw.copy() _fig, ax = plt.subplots(figsize=(11, 6.4)) ax.plot( x, lw, "s--", color=COLOR_MUTED, linewidth=1.4, markersize=6, label="$L_W$ = 95 dB (source power)", zorder=4, ) terms = ( (att.a_div, r"$-A_{\mathrm{div}}$ (divergence)", COLOR_PRIMARY), (att.a_atm, r"$-A_{\mathrm{atm}}$ (air)", COLOR_TERTIARY), (att.a_gr, r"$-A_{\mathrm{gr}}$ (ground)", "#9467bd"), (att.a_bar, r"$-A_{\mathrm{bar}}$ (barrier)", COLOR_SECONDARY), ) for term, label, color in terms: ax.bar( x, -np.asarray(term), bottom=level, color=color, alpha=0.85, width=0.62, label=label, zorder=2, ) level = level - np.asarray(term) ax.plot( x, level, "D-", color=COLOR_FG, linewidth=2.0, markersize=6, label=r"$L_{fT}(\mathrm{DW})$ at the receiver", zorder=5, ) ax.axhline(0.0, color=COLOR_MUTED, linewidth=0.9, zorder=1) ax.set_title("Where 95 dB of Source Power Goes (ISO 9613-2, 200 m)", pad=12) ax.set_xticks(x) ax.set_xticklabels([f"{b:g}" for b in bands]) ax.set_xlabel(LABEL_FREQ_HZ) ax.set_ylabel("Level [dB]") ax.grid(axis="y", color=COLOR_GRID, linestyle="--", alpha=0.5, zorder=0) ax.set_axisbelow(True) ax.legend(loc="lower left", fontsize=9, ncol=2) plt.tight_layout() save_figure(output_dir, "outdoor_level_cascade.svg") plt.close() def generate_iso9613_screening_anatomy(output_dir: str) -> None: """The ISO 9613-2 screening term: the caps, Kmet and the spent ground effect.""" print("Generating iso9613_screening_anatomy.svg...") from phonometry import environment heights = np.linspace(1.6, 12.0, 90) single, double = [], [] for h in heights: leg = float(np.hypot(100.0, h - 1.5)) single.append( float( environment.barrier_attenuation( environment.Barrier(source_to_edge=leg, edge_to_receiver=leg), 200.0, [500.0], )[0] ) ) double.append( float( environment.barrier_attenuation( environment.Barrier( source_to_edge=leg, edge_to_receiver=leg, edge_separation=2.0 ), 200.0, [500.0], )[0] ) ) bands = np.array([63.0, 125.0, 250.0, 500.0, 1000.0, 2000.0, 4000.0, 8000.0]) barrier = environment.Barrier(source_to_edge=101.0, edge_to_receiver=101.0) dz = np.asarray(environment.barrier_attenuation(barrier, 200.0, bands)) att = environment.outdoor_propagation_attenuation( 200.0, 1.5, 1.5, frequencies=bands, ground_source=1.0, ground_middle=1.0, ground_receiver=1.0, barrier=barrier, temperature_c=15.0, relative_humidity_percent=70.0, ) _fig, (left, right) = plt.subplots(1, 2, figsize=(12.5, 5.6)) left.plot( heights, single, color=COLOR_PRIMARY, linewidth=2.0, label="Single edge", zorder=4, ) left.plot( heights, double, color=COLOR_TERTIARY, linewidth=2.0, label="Double edge, $e$ = 2 m", zorder=4, ) left.axhline( 20.0, color=COLOR_SECONDARY, linestyle=":", linewidth=1.6, label="20 dB cap (single)", zorder=3, ) left.axhline( 25.0, color="#9467bd", linestyle=":", linewidth=1.6, label="25 dB cap (double)", zorder=3, ) left.set_title("$D_z$ at 500 Hz against barrier height ($d$ = 200 m)", pad=10) left.set_xlabel("Barrier height [m]") left.set_ylabel("Diffraction insertion loss $D_z$ [dB]") left.grid(color=COLOR_GRID, linestyle="--", alpha=0.5, zorder=0) left.set_axisbelow(True) left.legend(loc="lower right", fontsize=9) x = np.arange(bands.size) right.plot( x, dz, "o-", color=COLOR_PRIMARY, linewidth=2.0, markersize=6, label="$D_z$ (Eq. (14))", zorder=4, ) right.plot( x, att.a_bar, "D-", color=COLOR_SECONDARY, linewidth=2.0, markersize=6, label=r"$A_{\mathrm{bar}} = \max(D_z - A_{\mathrm{gr}}, 0)$ (Eq. (12))", zorder=4, ) right.fill_between( x, att.a_bar, dz, color=COLOR_TERTIARY, alpha=0.20, label=r"$A_{\mathrm{gr}}$, spent on the screened path", zorder=2, ) right.axhline(20.0, color=COLOR_MUTED, linestyle=":", linewidth=1.2, zorder=1) right.set_title("The ground effect is spent, not kept", pad=10) right.set_xticks(x) right.set_xticklabels([f"{b:g}" for b in bands]) right.set_xlabel(LABEL_FREQ_HZ) right.set_ylabel("Attenuation [dB]") right.grid(color=COLOR_GRID, linestyle="--", alpha=0.5, zorder=0) right.set_axisbelow(True) right.legend(loc="upper left", fontsize=9) plt.tight_layout() save_figure(output_dir, "iso9613_screening_anatomy.svg") plt.close() def generate_ground_reflection_coefficient(output_dir: str) -> None: """The ground wave: Q departing from Rp as the geometry grazes.""" print("Generating ground_reflection_coefficient.svg...") import warnings as _warnings from phonometry import environment heights = np.geomspace(3.0, 0.02, 120) c0, freq, dist = 343.0, 500.0, 50.0 k = 2.0 * np.pi * freq / c0 rp_mag, q_mag, dl_q, dl_p = [], [], [], [] with _warnings.catch_warnings(): _warnings.simplefilter("ignore") for h in heights: res = environment.ground_effect( [freq], float(h), float(h), dist, flow_resistivity_pa_s_m2=2e5, model="miki", ) rp = complex(res.plane_reflection_coefficient[0]) q = complex(res.reflection_coefficient[0]) ratio = float(res.r_direct) / float(res.r_reflected) phase = np.exp(1j * k * (float(res.r_reflected) - float(res.r_direct))) rp_mag.append(abs(rp)) q_mag.append(abs(q)) dl_q.append(20.0 * np.log10(abs(1.0 + q * ratio * phase))) dl_p.append(20.0 * np.log10(abs(1.0 + rp * ratio * phase))) _fig, (left, right) = plt.subplots(1, 2, figsize=(12.5, 5.4)) left.semilogx( heights, rp_mag, color=COLOR_PRIMARY, linewidth=2.0, label=r"$|R_{\mathrm{p}}|$: plane wave", zorder=4, ) left.semilogx( heights, q_mag, color=COLOR_SECONDARY, linewidth=2.0, label="$|Q|$: spherical wave", zorder=4, ) left.invert_xaxis() left.set_title("The coefficients part as the path grazes", pad=10) left.set_xlabel("Source = receiver height [m] (grazing to the right)") left.set_ylabel("Magnitude") left.grid(which="both", color=COLOR_GRID, linestyle="--", alpha=0.5, zorder=0) left.set_axisbelow(True) left.legend(loc="upper left", fontsize=9) right.semilogx( heights, dl_q, color=COLOR_SECONDARY, linewidth=2.0, label="with $Q$ (spherical wave)", zorder=4, ) right.semilogx( heights, dl_p, color=COLOR_PRIMARY, linewidth=2.0, linestyle="--", label=r"with $R_{\mathrm{p}}$ alone (plane wave)", zorder=4, ) right.invert_xaxis() right.axhline(0.0, color=COLOR_MUTED, linewidth=0.9, zorder=1) right.annotate( f"{_fmt_minus(dl_q[-1], '.1f')} dB against {_fmt_minus(dl_p[-1], '.1f')} dB", xy=(float(heights[-1]), dl_q[-1]), xytext=(0.30, 0.18), textcoords="axes fraction", fontsize=10, color=COLOR_FG, arrowprops={"arrowstyle": "->", "color": COLOR_MUTED}, ) right.set_title("What the ground wave keeps alive (500 Hz, 50 m)", pad=10) right.set_xlabel("Source = receiver height [m] (grazing to the right)") right.set_ylabel("Level re free field [dB]") right.grid(which="both", color=COLOR_GRID, linestyle="--", alpha=0.5, zorder=0) right.set_axisbelow(True) right.legend(loc="lower left", fontsize=9) plt.tight_layout() save_figure(output_dir, "ground_reflection_coefficient.svg") plt.close() def generate_barrier_thickness_gain(output_dir: str) -> None: """What a thick barrier actually buys, in two models.""" print("Generating barrier_thickness_gain.svg...") import math import warnings as _warnings from phonometry import environment widths = np.linspace(0.0, 30.0, 46) _fig, (left, right) = plt.subplots(1, 2, figsize=(12.5, 5.4)) with _warnings.catch_warnings(): _warnings.simplefilter("ignore") for freq, color in ( (250.0, COLOR_PRIMARY), (500.0, COLOR_TERTIARY), (1000.0, COLOR_SECONDARY), ): thin = float( environment.barrier_insertion_loss( [freq], 1.0, 50.0, 4.0, 100.0, 1.5, method="exact" ).insertion_loss[0] ) gain = [] for e in widths: if e <= 0.0: gain.append(0.0) continue gain.append( float( environment.barrier_insertion_loss( [freq], 1.0, 50.0, 4.0, 100.0, 1.5, method="exact", thickness_m=float(e), ).insertion_loss[0] ) - thin ) left.plot( widths, gain, color=color, linewidth=2.0, label=f"{freq:g} Hz", zorder=4 ) left.set_title("Wave-theoretic model: the path length alone", pad=10) left.set_xlabel("Top width $e$ [m]") left.set_ylabel("Gain over the thin screen [dB]") left.set_ylim(-0.1, 5.0) left.grid(color=COLOR_GRID, linestyle="--", alpha=0.5, zorder=0) left.set_axisbelow(True) left.legend(loc="upper left", fontsize=9) dss = math.hypot(50.0, 3.0) for freq, color in ( (250.0, COLOR_PRIMARY), (500.0, COLOR_TERTIARY), (1000.0, COLOR_SECONDARY), ): thin = float( environment.barrier_attenuation( environment.Barrier( source_to_edge=dss, edge_to_receiver=math.hypot(50.0, 2.5) ), 100.0, [freq], )[0] ) gain = [] for e in widths: if e <= 0.0: gain.append(0.0) continue dsr = math.hypot(50.0 - float(e), 2.5) gain.append( float( environment.barrier_attenuation( environment.Barrier( source_to_edge=dss, edge_to_receiver=dsr, edge_separation=float(e), ), 100.0, [freq], )[0] ) - thin ) right.plot( widths, gain, color=color, linewidth=2.0, label=f"{freq:g} Hz", zorder=4 ) right.axhline( 10.0 * np.log10(3.0), color=COLOR_MUTED, linestyle=":", linewidth=1.4, label=r"$10\,\mathrm{lg}\,3 = 4.77$ dB (the $C_3$ ceiling)", zorder=3, ) right.set_title("ISO 9613-2: the path length plus the $C_3$ factor", pad=10) right.set_xlabel("Edge separation $e$ [m]") right.set_ylabel("Gain over the single edge [dB]") right.grid(color=COLOR_GRID, linestyle="--", alpha=0.5, zorder=0) right.set_axisbelow(True) right.legend(loc="lower right", fontsize=9) plt.tight_layout() save_figure(output_dir, "barrier_thickness_gain.svg") plt.close() def generate_shadow_zone_map(output_dir: str) -> None: """Is my range long enough for refraction to matter?""" print("Generating shadow_zone_map.svg...") from phonometry import environment gradients = np.geomspace(0.02, 0.4, 160) _fig, ax = plt.subplots(figsize=(11, 6.2)) pairs = ( (0.5, 1.5, COLOR_PRIMARY), (2.0, 2.0, COLOR_TERTIARY), (2.0, 10.0, COLOR_SECONDARY), ) for hs, hr, color in pairs: ax.loglog( gradients, [ environment.shadow_zone_distance( -float(g), hs, hr, ground_speed_of_sound=340.0 ) for g in gradients ], color=color, linewidth=2.0, label=rf"$h_{{\mathrm{{s}}}}/h_{{\mathrm{{r}}}}$ = " rf"{hs:g} / {hr:g} m", zorder=4, ) ax.axvline(0.1, color=COLOR_MUTED, linestyle="--", linewidth=1.3, zorder=2) ax.plot( [0.1], [environment.shadow_zone_distance(-0.1, 2.0, 2.0, ground_speed_of_sound=340.0)], "o", color=COLOR_FG, markersize=8, zorder=5, ) ax.annotate( "representative −0.1 s⁻¹: 233 m", xy=(0.1, 233.2), xytext=(0.022, 90.0), fontsize=10, color=COLOR_FG, arrowprops={"arrowstyle": "->", "color": COLOR_MUTED}, ) grad_log = 1.0 * np.log(101.0) / 10.0 ax.plot( [grad_log], [ environment.shadow_zone_distance( -grad_log, 2.0, 2.0, ground_speed_of_sound=340.0 ) ], "s", color=COLOR_SECONDARY, markersize=8, zorder=5, ) ax.annotate( "the page's $b$ = −1 m/s case: 109 m", xy=(grad_log, 108.6), xytext=(0.12, 480.0), fontsize=10, color=COLOR_FG, arrowprops={"arrowstyle": "->", "color": COLOR_MUTED}, ) ax.set_title("Where the Acoustic Shadow Starts ($c_0$ = 340 m/s)", pad=12) ax.set_xlabel("Upward sound-speed gradient $|g|$ [1/s]") ax.set_ylabel(r"Shadow-zone distance $x_{\mathrm{shadow}}$ [m]") ax.grid(which="both", color=COLOR_GRID, linestyle="--", alpha=0.5, zorder=0) ax.set_axisbelow(True) ax.legend(loc="upper right", fontsize=10) secondary = ax.secondary_xaxis( "top", functions=( lambda g: 340.0 / np.maximum(g, 1e-9), lambda r: 340.0 / np.maximum(r, 1e-9), ), ) secondary.set_xlabel(r"Radius of curvature $R_{\mathrm{c}} = c_0/|g|$ [m]") plt.tight_layout() save_figure(output_dir, "shadow_zone_map.svg") plt.close() def generate_refraction_homogeneous_check(output_dir: str) -> None: """The GFPE against the coherent two-ray field with the gradient switched off.""" print("Generating refraction_homogeneous_check.svg...") import warnings as _warnings from phonometry import environment c0, freq, zs = 343.0, 500.0, 2.0 flat = environment.linear_sound_speed_profile( 1e-12, ground_speed_of_sound=c0, max_height_m=200.0 ) with _warnings.catch_warnings(): _warnings.simplefilter("ignore") pe = environment.atmospheric_parabolic_equation( freq, flat, source_height_m=zs, impedance=1e6 + 0j, max_range=520.0, max_height_m=150.0, ) ranges = np.asarray(pe.ranges) solver = np.asarray(pe.level_at_height(zs)) k = 2.0 * np.pi * freq / c0 r1 = np.hypot(ranges, 0.0) r2 = np.hypot(ranges, 2.0 * zs) two_ray = 20.0 * np.log10(np.abs(1.0 + (r1 / r2) * np.exp(1j * k * (r2 - r1)))) _fig, (top, bottom) = plt.subplots( 2, 1, figsize=(11, 7.2), sharex=True, gridspec_kw={"height_ratios": [2.2, 1.0]} ) top.plot( ranges, solver, color=COLOR_PRIMARY, linewidth=1.8, label="GFPE, zero gradient", zorder=4, ) top.plot( ranges, two_ray, color=COLOR_SECONDARY, linewidth=1.6, linestyle="--", label="Coherent two-ray closed form", zorder=4, ) top.axhline( 6.0, color=COLOR_MUTED, linestyle=":", linewidth=1.3, label="+6 dB (coherent sum)", zorder=2, ) top.set_ylim(-35.0, 10.0) top.set_ylabel("Level re free field [dB]") top.set_title( "The Homogeneous Limit: 500 Hz, Rigid Ground, " r"$h_{\mathrm{s}} = h_{\mathrm{r}}$ = 2 m", pad=12, ) top.grid(color=COLOR_GRID, linestyle="--", alpha=0.5, zorder=0) top.set_axisbelow(True) top.legend(loc="lower right", fontsize=9) bottom.plot(ranges, solver - two_ray, color=COLOR_TERTIARY, linewidth=1.6, zorder=4) bottom.axhline(0.6, color=COLOR_MUTED, linestyle=":", linewidth=1.3, zorder=2) bottom.axhline(-0.6, color=COLOR_MUTED, linestyle=":", linewidth=1.3, zorder=2) bottom.axhline(0.0, color=COLOR_MUTED, linewidth=0.9, zorder=2) bottom.set_ylim(-6.0, 18.0) bottom.set_xlabel("Range [m]") bottom.set_ylabel("Residual [dB]") bottom.grid(color=COLOR_GRID, linestyle="--", alpha=0.5, zorder=0) bottom.set_axisbelow(True) bottom.text( 0.98, 0.90, "dotted lines: ±0.6 dB", transform=bottom.transAxes, ha="right", va="top", fontsize=9, color=COLOR_MUTED, ) plt.tight_layout() save_figure(output_dir, "refraction_homogeneous_check.svg") plt.close() def generate_cnossos_road_corrections(output_dir: str) -> None: """Temperature, studded tyres and junctions, as changes in the line power.""" print("Generating cnossos_road_corrections.svg...") from phonometry import environment def a_line(**kwargs: Any) -> float: return float(environment.road_source_power(**kwargs).a_weighted_line_power) light = [ environment.RoadTraffic( category=environment.RoadVehicleCategory.LIGHT, flow_rate=1000.0, speed_kmh=50.0, ) ] heavy = [ environment.RoadTraffic( category=environment.RoadVehicleCategory.HEAVY, flow_rate=1000.0, speed_kmh=50.0, ) ] _fig, (t_ax, s_ax, j_ax) = plt.subplots(1, 3, figsize=(14.5, 4.8)) temps = np.linspace(-10.0, 40.0, 60) for flow, name, color in ( (light, "Light (1)", COLOR_PRIMARY), (heavy, "Heavy (3)", COLOR_SECONDARY), ): ref = a_line(traffic=flow) t_ax.plot( temps, [a_line(traffic=flow, temperature_c=float(t)) - ref for t in temps], color=color, linewidth=2.0, label=name, zorder=4, ) t_ax.axvline(20.0, color=COLOR_MUTED, linestyle=":", linewidth=1.3, zorder=2) t_ax.axhline(0.0, color=COLOR_MUTED, linewidth=0.9, zorder=1) t_ax.set_title("Air temperature (2.2.10)", pad=10) t_ax.set_xlabel(r"Air temperature $\tau$ [°C]") t_ax.set_ylabel("Change in line power [dB(A)]") t_ax.legend(loc="upper right", fontsize=9) speeds = np.linspace(20.0, 130.0, 56) for share, color in ((0.2, COLOR_PRIMARY), (0.5, COLOR_TERTIARY)): s_ax.plot( speeds, [ a_line( traffic=[ environment.RoadTraffic( category=environment.RoadVehicleCategory.LIGHT, flow_rate=1000.0, speed_kmh=float(v), studded_fraction=share, ) ], studded_months=4.0, ) - a_line( traffic=[ environment.RoadTraffic( category=environment.RoadVehicleCategory.LIGHT, flow_rate=1000.0, speed_kmh=float(v), ) ] ) for v in speeds ], color=color, linewidth=2.0, label=rf"$Q_{{\mathrm{{stud}}}}$ = {share:g}, " rf"$T_{{\mathrm{{s}}}}$ = 4 months", zorder=4, ) for edge in (50.0, 90.0): s_ax.axvline(edge, color=COLOR_MUTED, linestyle=":", linewidth=1.3, zorder=2) s_ax.set_title("Studded tyres (2.2.6-2.2.9)", pad=10) s_ax.set_xlabel("Speed $v$ [km/h]") s_ax.set_ylabel("Change in line power [dB(A)]") s_ax.legend(loc="upper right", fontsize=8) xs = np.linspace(0.0, 120.0, 61) ref = a_line(traffic=light) for junction, name, color in ( ( environment.JunctionType.CROSSING, "Crossing with lights", COLOR_PRIMARY, ), (environment.JunctionType.ROUNDABOUT, "Roundabout", COLOR_SECONDARY), ): j_ax.plot( xs, [ a_line( traffic=light, junction_distance=float(x), junction_type=junction ) - ref for x in xs ], color=color, linewidth=2.0, label=name, zorder=4, ) j_ax.axvline(100.0, color=COLOR_MUTED, linestyle=":", linewidth=1.3, zorder=2) j_ax.axhline(0.0, color=COLOR_MUTED, linewidth=0.9, zorder=1) j_ax.set_title("Junctions (2.2.17, 2.2.18)", pad=10) j_ax.set_xlabel("Distance to the junction $|x|$ [m]") j_ax.set_ylabel("Change in line power [dB(A)]") j_ax.legend(loc="lower right", fontsize=9) for ax in (t_ax, s_ax, j_ax): ax.grid(color=COLOR_GRID, linestyle="--", alpha=0.5, zorder=0) ax.set_axisbelow(True) plt.tight_layout() save_figure(output_dir, "cnossos_road_corrections.svg") plt.close() def generate_cnossos_road_gradient(output_dir: str) -> None: """The asymmetric road-gradient correction to propulsion noise.""" print("Generating cnossos_road_gradient.svg...") from phonometry import environment weights = np.asarray(environment.CNOSSOS_A_WEIGHTING) def a_weighted(bands: NDArray[np.float64]) -> float: return float( 10.0 * np.log10(np.sum(10.0 ** ((np.asarray(bands) + weights) / 10.0))) ) slopes = np.linspace(-14.0, 14.0, 141) _fig, ax = plt.subplots(figsize=(11, 6.4)) colors: dict[RoadVehicleCode, str] = { "1": COLOR_PRIMARY, "2": COLOR_TERTIARY, "3": COLOR_SECONDARY, } for category, color in colors.items(): for speed, style in ((50.0, "--"), (80.0, "-")): flat = a_weighted(environment.road_propulsion_noise(category, speed)) ax.plot( slopes, [ a_weighted( environment.road_propulsion_noise( category, speed, road_slope_percent=float(s) ) ) - flat for s in slopes ], style, color=color, linewidth=1.9, label=f"Category {category}, {speed:g} km/h", zorder=4, ) for edge in (-12.0, 12.0): ax.axvline(edge, color=COLOR_MUTED, linestyle=":", linewidth=1.3, zorder=2) ax.axhline(0.0, color=COLOR_MUTED, linewidth=0.9, zorder=1) ax.set_title("CNOSSOS-EU Road-Gradient Correction (2.2.13-2.2.16)", pad=12) ax.set_xlabel("Road gradient $s$ [%] (negative = downhill)") ax.set_ylabel("Propulsion-noise correction [dB(A)]") ax.grid(color=COLOR_GRID, linestyle="--", alpha=0.5, zorder=0) ax.set_axisbelow(True) ax.legend(loc="upper center", fontsize=9, ncol=3) plt.tight_layout() save_figure(output_dir, "cnossos_road_gradient.svg") plt.close() def generate_cnossos_road_surfaces(output_dir: str) -> None: """Table F-4: the octave-band surface coefficient of five pavements.""" print("Generating cnossos_road_surfaces.svg...") from phonometry import environment bands = np.array([63.0, 125.0, 250.0, 500.0, 1000.0, 2000.0, 4000.0, 8000.0]) rows = ( (environment.RoadSurface.REFERENCE, COLOR_FG, ":"), (environment.RoadSurface.TWO_LAYER_ZOAB_FINE, COLOR_PRIMARY, "-"), (environment.RoadSurface.ONE_LAYER_ZOAB, COLOR_TERTIARY, "-"), (environment.RoadSurface.THIN_LAYER_A, "#9467bd", "-"), (environment.RoadSurface.SMA_NL8, "#e8a838", "-"), ( environment.RoadSurface.HARD_ELEMENTS_NOT_HERRINGBONE, COLOR_SECONDARY, "-", ), ) _fig, ax = plt.subplots(figsize=(11, 6.4)) for surface, color, style in rows: row = environment.road_surface_coefficients(surface) span = ( "all speeds" if row.speed_range_kmh is None else "{:g}-{:g} km/h".format(*row.speed_range_kmh) ) ax.semilogx( bands, np.asarray(row.alpha["1"]), style, color=color, marker="o", markersize=5, linewidth=1.9, markerfacecolor="white", markeredgewidth=1.2, label=f"{surface.value} ({span})", zorder=4, ) ax.axhline(0.0, color=COLOR_MUTED, linewidth=0.9, zorder=1) ax.set_title("CNOSSOS-EU Road Surfaces (Table F-4, light vehicles)", pad=12) ax.set_xlabel(LABEL_FREQ_HZ) ax.set_ylabel(r"Surface coefficient $\alpha$ [dB]") ax.set_xlim(63.0, 8000.0) format_frequency_axis(ax, 63.0, 8000.0, language=_LANG) ax.grid(which="both", color=COLOR_GRID, linestyle="--", alpha=0.5, zorder=0) ax.set_axisbelow(True) ax.legend(loc="upper right", fontsize=8.5) plt.tight_layout() save_figure(output_dir, "cnossos_road_surfaces.svg") plt.close() def generate_cnossos_rail_components(output_dir: str) -> None: """Which source line carries what, and when source B wakes up.""" print("Generating cnossos_rail_components.svg...") from phonometry import environment stock, track = _cnossos_rail_scene() def total(bands: NDArray[np.float64]) -> float: return float(10.0 * np.log10(np.sum(10.0 ** (np.asarray(bands) / 10.0)))) _fig, (left, right) = plt.subplots(1, 2, figsize=(13, 5.4)) result = environment.railway_source_power( environment.RailwayVehicle(stock=stock, flow_rate=96.0, speed_kmh=160.0), track, phi=90.0, psi=10.0, ) freqs = np.asarray(result.third_octave_frequencies) palette = { "rolling": COLOR_PRIMARY, "traction": COLOR_TERTIARY, "aerodynamic": COLOR_SECONDARY, "bridge": "#9467bd", } for name, spectrum in result.components.items(): for row, height, style in ((0, "0,5 m", "-"), (1, "4,0 m", "--")): values = np.asarray(spectrum)[row] if not np.any(np.isfinite(values)): continue left.semilogx( freqs, values, style, color=palette.get(name, COLOR_MUTED), linewidth=1.9, label=f"{name} @ {height}", zorder=4, ) left.set_title("Components at 160 km/h, by source height", pad=10) left.set_xlabel("1/3-octave band centre frequency [Hz]") left.set_ylabel("Sound power [dB re 1 pW]") left.set_xlim(50.0, 10000.0) format_frequency_axis(left, 50.0, 10000.0, language=_LANG) left.grid(which="both", color=COLOR_GRID, linestyle="--", alpha=0.5, zorder=0) left.set_axisbelow(True) left.legend(loc="lower center", fontsize=9) speeds = np.linspace(60.0, 350.0, 40) for row, label, color in ( (0, "Source A (0,5 m)", COLOR_PRIMARY), (1, "Source B (4,0 m)", COLOR_SECONDARY), ): right.plot( speeds, [ total( environment.railway_source_power( environment.RailwayVehicle( stock=stock, flow_rate=96.0, speed_kmh=float(v) ), track, phi=90.0, psi=10.0, ).line_power[row] ) for v in speeds ], color=color, linewidth=2.0, label=label, zorder=4, ) right.axvline( 200.0, color=COLOR_MUTED, linestyle=":", linewidth=1.4, label="Aerodynamic threshold (2.3.13)", zorder=2, ) right.set_title("Each source line against speed", pad=10) right.set_xlabel("Speed $v$ [km/h]") right.set_ylabel("Total line power [dB re 1 pW per metre]") right.grid(color=COLOR_GRID, linestyle="--", alpha=0.5, zorder=0) right.set_axisbelow(True) right.legend(loc="center right", fontsize=9) plt.tight_layout() save_figure(output_dir, "cnossos_rail_components.svg") plt.close() def generate_cnossos_rail_directivity(output_dir: str) -> None: """Two editions of the vertical correction, and the horizontal dipole.""" print("Generating cnossos_rail_directivity.svg...") from phonometry import environment psi = np.linspace(-89.0, 89.0, 179) fig, (left, right) = plt.subplots( 1, 2, subplot_kw={"projection": "polar"}, figsize=(12.5, 5.8) ) bands = ((7, "250 Hz", COLOR_PRIMARY), (19, "4 kHz", COLOR_SECONDARY)) for band, name, color in bands: for edition, style in ( (environment.DirectivityEdition.CURRENT, "-"), (environment.DirectivityEdition.ORIGINAL_2015, "--"), ): values = [ float(environment.vertical_directivity(float(a), edition=edition)[band]) for a in psi ] left.plot( np.radians(psi), values, style, color=color, linewidth=1.9, label=f"{name}, {edition.value}", ) left.set_title("Vertical correction of source A (2.3.16)", pad=18) left.set_thetamin(-90.0) left.set_thetamax(90.0) left.set_theta_zero_location("E") # The default theta formatter writes its negative angles with an ASCII # hyphen; restate the same grid with the typographic minus. left.set_thetagrids( np.arange(-90, 91, 30), [f"{_fmt_minus(a, '.0f')}°" for a in range(-90, 91, 30)] ) left.grid(color=COLOR_GRID, linestyle="--", alpha=0.6) # Beside the half disc, level with its 60° ray, in the room the half disc # leaves: in the lower corner the box covered the radial "15" and "−90°". left.legend(loc="upper left", fontsize=8, bbox_to_anchor=(0.78, 1.0)) phi = np.radians(np.linspace(0.0, 360.0, 361)) right.plot( phi, 10.0 * np.log10(0.01 + 0.99 * np.sin(phi) ** 2), color=COLOR_TERTIARY, linewidth=2.0, ) right.set_title("Horizontal dipole (2.3.15)", pad=18) right.set_theta_zero_location("E") # A ring every 2.5 dB and a label on every other one: nine labels on the # one ray ran into each other, and 5 dB apart they clear. rings = np.arange(-20.0, 0.1, 2.5) # Inside the upper lobe, where the curve runs out at the rim: at the # default 22.5° the lobe's flank ran through "−10.0", and nearer the track # the null at the centre runs through "−20.0". right.set_rgrids( rings, [_fmt_minus(r, ".1f") if i % 2 == 0 else "" for i, r in enumerate(rings)], angle=70.0, ) right.grid(color=COLOR_GRID, linestyle="--", alpha=0.6) right.annotate( "−20 dB along the track", xy=(0.0, -20.0), xytext=(0.35, 0.02), textcoords="figure fraction", fontsize=9, color=COLOR_FG, arrowprops={"arrowstyle": "->", "color": COLOR_MUTED}, ) fig.suptitle("CNOSSOS-EU Railway Source Directivity", fontsize=13) plt.tight_layout() save_figure(output_dir, "cnossos_rail_directivity.svg") plt.close() def generate_wind_turbine_apparent_power(output_dir: str) -> None: """LWA as a function of wind speed, with a voided and an asterisked bin.""" print("Generating wind_turbine_apparent_power.svg...") from phonometry import environment r1 = environment.slant_distance(hub_height_m=80.0, rotor_diameter_m=100.0) bins = np.arange(4.0, 12.5, 0.5) shape = np.array([-4.0, -1.5, 0.0, -1.0, -3.0]) # 250 Hz to 1 kHz lwa = np.array( [ float( environment.apparent_sound_power_level( 44.0 + 12.0 / (1.0 + np.exp(-(v - 7.0))) + shape, r1 ) ) for v in bins ] ) voided, flagged = 0, 1 # the two lowest bins, by their margin _fig, ax = plt.subplots(figsize=(11, 6.4)) ax.plot(bins, lwa, "-", color=COLOR_PRIMARY, linewidth=2.2, zorder=3) keep = np.ones(bins.size, dtype=bool) keep[[voided, flagged]] = False ax.plot( bins[keep], lwa[keep], "o", color=COLOR_PRIMARY, markersize=7, markerfacecolor="white", markeredgewidth=1.6, label="Valid bin (margin $>$ 6 dB)", zorder=5, ) ax.plot( [bins[flagged]], [lwa[flagged]], "o", color="#e8a838", markersize=9, label="3-6 dB margin: reported with an asterisk", zorder=5, ) ax.plot( [bins[voided]], [lwa[voided]], "x", color=COLOR_SECONDARY, markersize=12, markeredgewidth=2.4, label=r"Margin $\leq$ 3 dB: bin voided", zorder=5, ) ax.set_title("Apparent Sound Power against Wind Speed (IEC 61400-11)", pad=12) ax.set_xlabel("Hub-height wind speed [m/s] (0,5 m/s bins)") ax.set_ylabel(r"$L_{W\!\mathrm{A}}$ [dB(A) re 1 pW]") ax.grid(color=COLOR_GRID, linestyle="--", alpha=0.5, zorder=0) ax.set_axisbelow(True) ax.legend(loc="lower right", fontsize=9) # Formula (29): the same series against the 10 m reference-roughness speed. z0ref, hub = 0.05, 80.0 factor = np.log(10.0 / z0ref) / np.log(hub / z0ref) secondary = ax.secondary_xaxis( "top", functions=(lambda v: v * factor, lambda v: v / factor) ) secondary.set_xlabel( r"Formula (29) wind speed at 10 m, $z_{0\mathrm{ref}}$ = 0,05 m [m/s]" ) plt.tight_layout() save_figure(output_dir, "wind_turbine_apparent_power.svg") plt.close() def generate_wind_turbine_audibility_criterion(output_dir: str) -> None: """The critical bandwidth and the audibility criterion against frequency.""" print("Generating wind_turbine_audibility_criterion.svg...") from phonometry import environment fc = np.geomspace(20.0, 10000.0, 400) zwicker = 25.0 + 75.0 * (1.0 + 1.4 * (fc / 1000.0) ** 2) ** 0.69 la = -2.0 - np.log10(1.0 + (fc / 502.0) ** 2.5) _fig, (left, right) = plt.subplots(1, 2, figsize=(12.5, 5.2)) left.loglog( fc, zwicker, color=COLOR_PRIMARY, linewidth=2.0, label="IEC 61400-11 critical band (Zwicker)", zorder=4, ) left.loglog( fc, [environment.critical_bandwidth(float(f)) for f in fc], "--", color=COLOR_TERTIARY, linewidth=1.8, label="ISO 1996-2 Table C.1", zorder=4, ) left.plot( [20.0, 70.0], [100.0, 100.0], color=COLOR_SECONDARY, linewidth=5.0, solid_capstyle="butt", label="9.5.3: fixed 20-120 Hz band", zorder=5, ) left.set_title("Two critical bandwidths on one page", pad=10) left.set_xlabel(r"Tone frequency $f_{\mathrm{c}}$ [Hz]") left.set_ylabel("Critical bandwidth [Hz]") left.set_xlim(20.0, 10000.0) format_frequency_axis(left, 20.0, 10000.0, language=_LANG) left.grid(which="both", color=COLOR_GRID, linestyle="--", alpha=0.5, zorder=0) left.set_axisbelow(True) left.legend(loc="upper left", fontsize=8.5) right.semilogx( fc, -la, color=COLOR_PRIMARY, linewidth=2.0, label=r"Tonality needed to be audible " r"($\Delta L_{\mathrm{a}} > 0$)", zorder=4, ) right.semilogx( fc, -la - 3.0, "--", color=COLOR_SECONDARY, linewidth=1.8, label=r"Tonality needed to be reportable " r"($\Delta L_{\mathrm{a}} \geq -3$ dB)", zorder=4, ) right.axhline(0.0, color=COLOR_MUTED, linewidth=0.9, zorder=1) right.set_title("The audibility criterion, read as required tonality", pad=10) right.set_xlabel("Tone frequency [Hz]") right.set_ylabel(r"Required tonality $\Delta L_{\mathrm{tn}}$ [dB]") right.set_xlim(20.0, 10000.0) format_frequency_axis(right, 20.0, 10000.0, language=_LANG) right.grid(which="both", color=COLOR_GRID, linestyle="--", alpha=0.5, zorder=0) right.set_axisbelow(True) right.legend(loc="upper left", fontsize=8.5) plt.tight_layout() save_figure(output_dir, "wind_turbine_audibility_criterion.svg") plt.close() # --------------------------------------------------------------------------- # IEC TS 61400-11-2: wind turbine sound at a receptor # --------------------------------------------------------------------------- def _wt_text(english: str, spanish: str) -> str: """The label in the language being drawn (these panels are the script's own).""" return spanish if _LANG == "es" else english def _wt_receptor_campaign() -> tuple["BinnedSoundLevels", "BinnedSoundLevels"]: """A receptor campaign: 10 min totals with the turbines on and a background. The turbine level grows 2 dB per m/s up to its rated wind speed of 9 m/s and then holds; the background grows 3.4 dB per m/s from the trees, so the two meet in the top bins, where 11.7 stops subtracting. """ from phonometry import environment rng = np.random.default_rng(611) speeds = rng.uniform(2.6, 11.45, 420) turbine = 33.0 + 2.0 * np.minimum(speeds, 9.0) background = 15.0 + 3.4 * speeds total = 10.0 * np.log10(10.0 ** (turbine / 10.0) + 10.0 ** (background / 10.0)) total_levels = np.round(total + rng.normal(0.0, 1.2, speeds.size), 1) off_speeds = rng.uniform(2.6, 11.45, 240) off_levels = np.round(15.0 + 3.4 * off_speeds + rng.normal(0.0, 1.5, 240), 1) binned = environment.bin_sound_levels( total_levels, speeds, type_b_uncertainty_db=0.5 ) off = environment.bin_sound_levels( off_levels, off_speeds, type_b_uncertainty_db=0.5 ) return binned, off def generate_wind_turbine_receptor_bins(output_dir: str) -> None: """IEC TS 61400-11-2 10.3 and 11.7: bin averages and the background.""" print("Generating wind_turbine_receptor_bins...") binned, off = _wt_receptor_campaign() fig, (left, right) = plt.subplots(1, 2, figsize=(13.0, 5.4)) binned.plot(left, language=_LANG) left.set_title( _wt_text( "Total level per 1 m/s bin, Equations (1) to (5)", "Nivel total por intervalo de 1 m/s, ecuaciones (1) a (5)", ) ) binned.background_corrected(off).plot(right, language=_LANG) fig.tight_layout() save_figure(output_dir, "wind_turbine_receptor_bins.svg") plt.close() def generate_wind_turbine_receptor_shear(output_dir: str) -> None: """IEC TS 61400-11-2 Annex K and 9.3.2.3: shear and relevant turbines.""" print("Generating wind_turbine_receptor_shear...") from phonometry import environment profile = environment.wind_shear_profile(4.5, 8.6, upper_height_m=120.0) relevant = environment.sound_relevant_turbines( [33.5, 38.2, 29.4, 36.9, 25.1, 31.8, 27.0] ) fig, (left, right) = plt.subplots(1, 2, figsize=(13.0, 5.4)) profile.plot(left, language=_LANG) relevant.plot(right, language=_LANG) right.set_title( _wt_text( "Sound relevant turbines (9.3.2.3)", "Aerogeneradores relevantes para el sonido (9.3.2.3)", ) ) fig.tight_layout() save_figure(output_dir, "wind_turbine_receptor_shear.svg") plt.close() def _wt_low_frequency() -> "LowFrequencyLevel": """Three 120 m turbines at 650 m, 820 m and 1100 m, indoors behind brick.""" from phonometry import environment power = 118.0 - np.arange(environment.LOW_FREQUENCY_BANDS_HZ.size, dtype=float) return environment.wind_turbine_low_frequency_level( np.vstack([power, power, power - 1.0]), distance=[650.0, 820.0, 1100.0], hub_height_m=120.0, facade_insulation=environment.LOW_FREQUENCY_FACADE_INSULATION[ "Denmark brick or similar" ], ) def generate_wind_turbine_receptor_low_frequency(output_dir: str) -> None: """IEC TS 61400-11-2 Annex C: Equation (C.1) and the air of Table C.2. The right panel is why Table C.2 sits under ISO 9613-1 at the atmosphere its caption names: from 25 Hz to 100 Hz its cells are the Danish order's 80 % values, from 125 Hz up they are ISO 9613-1 at 70 %. Each point is the printed cell minus ISO 9613-1 at the nominal band centre; the shaded strip is the half unit of the printed second decimal, inside which a cell and a computed value are the same number. """ print("Generating wind_turbine_receptor_low_frequency...") import warnings from matplotlib.ticker import FixedFormatter, FixedLocator, NullLocator from phonometry import environment from phonometry._plot.common import _format_freq from phonometry.environment.propagation.air_absorption import air_attenuation fig, (left, right) = plt.subplots(1, 2, figsize=(13.0, 5.4)) _wt_low_frequency().plot(left, language=_LANG) left.set_title( _wt_text( "Equation (C.1), three turbines, brick facade", "Ecuación (C.1), tres aerogeneradores, fachada de ladrillo", ) ) bands = np.asarray(environment.LOW_FREQUENCY_BANDS_HZ) table = np.asarray(environment.LOW_FREQUENCY_AIR_ATTENUATION_DB_PER_KM) shown = bands >= 25.0 right.axhspan( -0.005, 0.005, color=theme_fill(COLOR_PRIMARY, right), zorder=0, label=_wt_text( "Within the printed rounding (0.005 dB/km)", "Dentro del redondeo impreso (0,005 dB/km)", ), ) right.axhline(0.0, color=COLOR_MUTED, linewidth=0.9, zorder=1) for humidity, colour, marker in ( (70.0, COLOR_SECONDARY, "o"), (80.0, COLOR_TERTIARY, "s"), ): with warnings.catch_warnings(): # Below 50 Hz ISO 9613-1 is advisory; the table goes there anyway. warnings.simplefilter("ignore") computed = 1000.0 * np.asarray( air_attenuation( bands[shown], temperature_c=10.0, relative_humidity_percent=humidity, ) ) right.plot( bands[shown], table[shown] - computed, marker=marker, color=colour, linewidth=1.6, markersize=7, label=_wt_text( f"Table C.2 minus ISO 9613-1 at 10 °C, {humidity:.0f} %", f"Tabla C.2 menos ISO 9613-1 a 10 °C, {humidity:.0f} %", ), zorder=4, ) right.set_xscale("log") right.set_xlim(22.0, 225.0) right.set_ylim(-0.03, 0.06) format_frequency_axis(right, 22.0, 225.0, language=_LANG) # Every band of the panel is labelled, the 100 Hz and 125 Hz the title # turns on among them, not only the octave centres. right.xaxis.set_major_locator(FixedLocator(bands[shown].tolist())) right.xaxis.set_major_formatter( FixedFormatter([_format_freq(float(f), _LANG) for f in bands[shown]]) ) right.xaxis.set_minor_locator(NullLocator()) right.set_xlabel(_wt_text(LABEL_FREQ_HZ, "Frecuencia [Hz]")) right.set_ylabel( _wt_text(r"Difference in $\alpha$ [dB/km]", r"Diferencia de $\alpha$ [dB/km]") ) right.set_title( _wt_text( "Table C.2 is 80 % air up to 100 Hz, 70 % above", "La Tabla C.2 es aire al 80 % hasta 100 Hz y al 70 % por encima", ) ) right.grid(which="both", color=COLOR_GRID, linestyle="--", alpha=0.5, zorder=0) right.set_axisbelow(True) right.legend(loc="upper left", fontsize=9) fig.tight_layout() save_figure(output_dir, "wind_turbine_receptor_low_frequency.svg") plt.close() def _wt_modulated_levels( seconds: float, rng: np.random.Generator, depth_db: "ArrayLike", *, fundamental_hz: float = 0.8, ) -> NDArray[np.float64]: """Band-limited 100 ms levels with a blade-passage swish and its harmonic. ``depth_db`` is the peak-to-peak swing of the fundamental, one value or one per sample; the second harmonic carries a third of it, the level drifts slowly with the wind, and the logger rounds to 0.1 dB. """ t = np.arange(round(seconds / 0.1)) * 0.1 depth = np.broadcast_to(np.asarray(depth_db, dtype=float), t.shape) swish = 0.5 * depth * np.sin(2.0 * np.pi * fundamental_hz * t) harmonic = depth / 6.0 * np.sin(4.0 * np.pi * fundamental_hz * t + 0.9) drift = 1.2 * np.sin(2.0 * np.pi * t / 47.0) noise = rng.normal(0.0, 1.0, t.size) return np.round(38.0 + drift + swish + harmonic + noise, 1) def generate_wind_turbine_modulation_block(output_dir: str) -> None: """IEC TS 61400-11-2 13.6.2.3: one 10 s block, spectrum and series.""" print("Generating wind_turbine_modulation_block...") from phonometry import environment rng = np.random.default_rng(1340) block = environment.amplitude_modulation_block( _wt_modulated_levels(10.0, rng, 4.0), modulation_frequency_range_hz=(0.5, 1.1), ) fig, (left, right) = plt.subplots(1, 2, figsize=(13.0, 5.4)) block.plot(left, language=_LANG) block.plot(right, kind="series", language=_LANG) fig.tight_layout() save_figure(output_dir, "wind_turbine_modulation_block.svg") plt.close() def _wt_modulation_period() -> "ModulationPeriod": """A 10 min period whose swish fades in and out, with a gusty minute.""" from phonometry import environment rng = np.random.default_rng(1363) t = np.arange(6000) * 0.1 depth = 3.0 + 2.5 * np.sin(2.0 * np.pi * t / 600.0) ** 2 depth[(t >= 240.0) & (t < 330.0)] = 0.0 levels = _wt_modulated_levels(600.0, rng, depth) gust = (t >= 240.0) & (t < 330.0) levels[gust] = np.round(levels[gust] + rng.normal(0.0, 2.5, int(gust.sum())), 1) return environment.amplitude_modulation_period( levels, modulation_frequency_range_hz=(0.5, 1.1) ) def _wt_binned_modulation() -> "BinnedModulation": """A survey of 10 min ratings in three bands, binned by wind speed.""" from phonometry import environment rng = np.random.default_rng(1364) periods = 600 speeds = rng.uniform(3.5, 10.45, periods) # Each band swishes hardest at its own wind speeds: the low band in light # winds, the middle one around rated power, the high one above it. peaks = (5.0, 7.0, 9.0) heights = (2.5, 4.0, 4.5) ratings = np.column_stack( [ np.clip( 1.5 + height * np.exp(-(((speeds - peak) / 2.0) ** 2)) + rng.normal(0.0, 0.8, periods), 0.0, None, ) for peak, height in zip(peaks, heights, strict=True) ] ) # Periods with fewer than 30 valid blocks are rated 0 dB, most often where # no band swishes. audible = np.exp(-(((speeds - 7.0) / 2.5) ** 2)) unrated = rng.uniform(0.0, 1.0, periods) < 0.35 * (1.0 - audible) ratings[unrated] = 0.0 return environment.bin_amplitude_modulation(np.round(ratings, 2), speeds) def generate_wind_turbine_modulation_period(output_dir: str) -> None: """IEC TS 61400-11-2 13.6.3 and 13.6.4: the 10 min rating and the bins.""" print("Generating wind_turbine_modulation_period...") fig, (left, right) = plt.subplots(1, 2, figsize=(13.0, 5.4)) _wt_modulation_period().plot(left, language=_LANG) _wt_binned_modulation().plot(right, language=_LANG) right.set_title( _wt_text( "Worst band per 1 m/s bin, unrated periods at 0 dB", "Peor banda por intervalo de 1 m/s, periodos sin valorar a 0 dB", ) ) fig.tight_layout() save_figure(output_dir, "wind_turbine_modulation_period.svg") plt.close() def generate_wind_turbine_receptor_rating(output_dir: str) -> None: """IEC TS 61400-11-2 Annex A: Figure A.1 and the rating level.""" print("Generating wind_turbine_receptor_rating...") from phonometry import environment rating = _wt_modulation_period().rating_db k_am = float(environment.amplitude_modulation_adjustment(rating)) fig, (left, right) = plt.subplots(1, 2, figsize=(13.0, 5.4)) # Figure A.1 steps at 3 dB: the curve is drawn up the step, as printed. depth = np.concatenate([np.linspace(0.0, 3.0, 2), np.linspace(3.0, 12.0, 361)]) adjustment = np.asarray(environment.amplitude_modulation_adjustment(depth)) adjustment[1] = 0.0 left.plot( depth, adjustment, color=COLOR_PRIMARY, linewidth=2.2, label=_wt_text("Figure A.1", "Figura A.1"), ) shown_rating = f"{rating:.2f}" shown_k = f"{k_am:.1f}" if _LANG == "es": shown_rating = shown_rating.replace(".", ",") shown_k = shown_k.replace(".", ",") left.plot( [rating], [k_am], "o", color=COLOR_SECONDARY, markersize=9, zorder=5, label=_wt_text( f"10 min rating {shown_rating} dB: $K_\\mathrm{{am}}$ = {shown_k} dB", f"Valoración de 10 min {shown_rating} dB: $K_\\mathrm{{am}}$ = {shown_k} dB", ), ) left.set_xlim(0.0, 12.0) left.set_ylim(0.0, 6.0) left.set_xlabel(_wt_text("Modulation depth [dB]", "Profundidad de modulación [dB]")) left.set_ylabel( _wt_text(r"Adjustment $K_\mathrm{am}$ [dB]", r"Ajuste $K_\mathrm{am}$ [dB]") ) left.set_title( _wt_text( "Amplitude modulation adjustment (A.3)", "Ajuste por modulación de amplitud (A.3)", ) ) left.grid(color=COLOR_GRID, linestyle="--", alpha=0.5, zorder=0) left.set_axisbelow(True) left.legend(loc="lower right", fontsize=9) environment.wind_turbine_rating_level( 41.0, tonal_adjustment=2.0, amplitude_modulation_adjustment=k_am, ).plot(right, language=_LANG) fig.tight_layout() save_figure(output_dir, "wind_turbine_receptor_rating.svg") plt.close() def generate_wind_turbine_tone_search(output_dir: str) -> None: """IEC TS 61400-11-2 12.5.2.4: the upper frequency of the tone search.""" print("Generating wind_turbine_tone_search...") from phonometry import environment fig, ax = plt.subplots(figsize=(10.0, 5.6)) environment.upper_tone_search_frequency( 600.0, temperature_c=10.0, relative_humidity_percent=50.0 ).plot(ax, language=_LANG) fig.tight_layout() save_figure(output_dir, "wind_turbine_tone_search.svg") plt.close() def generate_rd1367_tonal_correction(output_dir: str) -> None: """RD 1367/2007: the Kt test applied to the guide's own spectrum.""" print("Generating rd1367_tonal_correction.svg...") from phonometry import environment freqs = [100, 125, 160, 200, 250, 315, 400, 500, 630, 800, 1000] levels = [58.0, 60.0, 59.0, 61.0, 72.0, 62.0, 60.0, 58.0, 56.0, 54.0, 52.0] result = environment.tonal_correction(levels, frequencies=freqs) _fig, ax = plt.subplots(figsize=(11, 6.4)) result.plot(ax=ax, language=_LANG) plt.tight_layout() save_figure(output_dir, "rd1367_tonal_correction.svg") plt.close() def generate_rd1367_kf_ki(output_dir: str) -> None: """The two step functions that decide Kf and Ki.""" print("Generating rd1367_kf_ki.svg...") from phonometry import environment diffs = np.linspace(0.0, 20.0, 401) kf = [ environment.low_frequency_correction(lceq=63.0 + float(d), laeq=63.0) for d in diffs ] ki = [ environment.impulsive_correction(laieq=63.0 + float(d), laeq=63.0) for d in diffs ] _fig, ax = plt.subplots(figsize=(11, 6.2)) ax.step( diffs, kf, where="post", color=COLOR_PRIMARY, linewidth=2.4, label=r"$K_{\mathrm{f}}$, from " r"$L_{\mathrm{Ceq},Ti} - L_{\mathrm{Aeq},Ti}$", zorder=4, ) ax.step( diffs, ki, where="post", color=COLOR_SECONDARY, linewidth=2.0, linestyle="--", label=r"$K_{\mathrm{i}}$, from " r"$L_{\mathrm{AIeq},Ti} - L_{\mathrm{Aeq},Ti}$", zorder=4, ) for edge in (10.0, 15.0): ax.axvline(edge, color=COLOR_MUTED, linestyle=":", linewidth=1.3, zorder=2) ax.plot( [13.0], [3.0], "o", color=COLOR_PRIMARY, markersize=9, zorder=5, label=r"worked example: $L_{\mathrm{f}}$ = 13 dB → " r"$K_{\mathrm{f}}$ = 3 dB", ) ax.plot( [5.0], [0.0], "s", color=COLOR_SECONDARY, markersize=9, zorder=5, label=r"worked example: $L_{\mathrm{i}}$ = 5 dB → " r"$K_{\mathrm{i}}$ = 0 dB", ) ax.set_title("RD 1367/2007: the Low-Frequency and Impulsive Corrections", pad=12) ax.set_xlabel("Level difference [dB]") ax.set_ylabel("Correction [dB]") ax.set_ylim(-0.6, 7.0) ax.grid(color=COLOR_GRID, linestyle="--", alpha=0.5, zorder=0) ax.set_axisbelow(True) ax.legend(loc="upper left", fontsize=9) plt.tight_layout() save_figure(output_dir, "rd1367_kf_ki.svg") plt.close() def generate_rd1367_vs_iso_tonal(output_dir: str) -> None: """The RD grades a spectrum the ISO survey method does not flag.""" print("Generating rd1367_vs_iso_tonal.svg...") from phonometry import environment freqs = np.array( [100, 125, 160, 200, 250, 315, 400, 500, 630, 800, 1000], dtype=float ) deep = np.array([58.0, 60.0, 59.0, 61.0, 72.0, 62.0, 60.0, 58.0, 56.0, 54.0, 52.0]) shallow = deep.copy() shallow[4] = 69.0 _fig, axes = plt.subplots(1, 2, figsize=(13, 5.8), sharey=True) for ax, spectrum, title in ( (axes[0], deep, r"$L_{\mathrm{t}}$ = 10.5 dB: both methods agree"), (axes[1], shallow, r"$L_{\mathrm{t}}$ = 7.5 dB: the verdicts split"), ): rd = environment.tonal_correction(spectrum, frequencies=freqs) flags = np.asarray( environment.assess_tonal_survey(spectrum, frequencies=freqs).prominent ) colors = [ COLOR_SECONDARY if i == 4 else COLOR_PRIMARY for i in range(spectrum.size) ] ax.bar( np.arange(spectrum.size), spectrum, color=colors, alpha=0.85, width=0.66, zorder=3, ) neighbours = np.full(spectrum.size, np.nan) neighbours[1:-1] = (spectrum[:-2] + spectrum[2:]) / 2.0 ax.plot( np.arange(spectrum.size), neighbours, "_", color=COLOR_FG, markersize=22, markeredgewidth=2.4, label="Arithmetic mean of the two neighbours", zorder=5, ) ax.set_title(title, pad=10) ax.set_xticks(np.arange(spectrum.size)) ax.set_xticklabels([f"{f:g}" for f in freqs], rotation=45) ax.set_xlabel("1/3-octave band centre frequency [Hz]") ax.set_ylim(40.0, 80.0) ax.grid(axis="y", color=COLOR_GRID, linestyle="--", alpha=0.5, zorder=0) ax.set_axisbelow(True) ax.text( 0.03, 0.97, f"RD 1367 tonal_correction: $K_{{\\mathrm{{t}}}}$ = " f"{rd.correction:.0f} dB\n" f"ISO 1996-2 survey flag at 250 Hz: {bool(flags[4])}\n" f"$L_{{\\mathrm{{t}}}}$ at 250 Hz = " f"{_fmt_minus(rd.differences[4], '.1f')} dB", transform=ax.transAxes, va="top", fontsize=10, color=COLOR_FG, bbox={"boxstyle": "round", "facecolor": COLOR_PANEL, "alpha": 0.9}, ) ax.legend(loc="upper right", fontsize=9) axes[0].set_ylabel("Band sound pressure level [dB]") plt.tight_layout() save_figure(output_dir, "rd1367_vs_iso_tonal.svg") plt.close() #: ISO/TR 17534-3:2015, 6.2.1: the geometry and the air every test case shares, #: and the octave bands their tables are written in. _QA_BANDS = np.array([63.0, 125.0, 250.0, 500.0, 1000.0, 2000.0, 4000.0, 8000.0]) _QA_SOURCE = (10.0, 10.0, 1.0) _QA_RECEIVER = (200.0, 50.0, 4.0) _QA_LW = 93.0 _QA_TEMPERATURE, _QA_HUMIDITY = 20.0, 70.0 #: The envelope the document declares for a result to count as correct, dB. _QA_ENVELOPE = 0.05 #: Tables 4, 5, 6, 9, 10, 15 and 18, row "L": the printed receiver levels, dB. _QA_PRINTED: dict[str, tuple[float, ...]] = { "T01": (39.90, 39.86, 39.70, 39.37, 38.95, 38.17, 35.47, 25.04), "T02": (39.90, 36.17, 33.02, 33.20, 36.11, 36.33, 33.63, 23.20), "T03": (39.90, 32.48, 26.33, 27.03, 33.27, 34.49, 31.79, 21.36), "T04": (39.90, 36.24, 35.23, 36.04, 36.95, 36.57, 33.87, 23.45), "T05": (34.90, 34.86, 34.71, 34.38, 33.95, 33.17, 30.48, 20.05), "T06": (39.88, 35.65, 29.70, 29.24, 34.82, 35.83, 33.13, 22.68), "T07": (35.36, 35.32, 35.16, 34.83, 34.40, 33.62, 30.92, 20.47), } def _qa_levels() -> dict[str, NDArray[np.float64]]: """The seven cases ISO 9613-2 can answer on its own, computed. Kept beside the figure rather than imported from the conformance domain: the domain is the oracle and must not grow a consumer, and the geometry is two tables of the document either way. """ from phonometry import environment as env d_p = math.hypot(_QA_RECEIVER[0] - _QA_SOURCE[0], _QA_RECEIVER[1] - _QA_SOURCE[1]) d_flat = math.hypot(d_p, _QA_RECEIVER[2] - _QA_SOURCE[2]) # Table 13: the ground rises 10 m under the receiver, so the ray gains 13 m. d_sloped = math.hypot(d_p, 13.0) segments = (40.88, 102.19, 51.10) air = env.AtmosphericConditions( temperature_c=_QA_TEMPERATURE, relative_humidity_percent=_QA_HUMIDITY ) def general(ground: env.GroundFactors, distance: float) -> NDArray[np.float64]: return np.asarray( env.predicted_receiver_level( np.full(len(_QA_BANDS), _QA_LW), env.PropagationGeometry( distance=distance, source_height_m=_QA_SOURCE[2], receiver_height_m=_QA_RECEIVER[2], projected_distance=d_p, ), frequencies=_QA_BANDS, ground=ground, atmosphere=air, ) ) def alternative(mean_height: float, distance: float) -> NDArray[np.float64]: return np.asarray( _QA_LW + env.directivity_omega(_QA_SOURCE[2], _QA_RECEIVER[2], d_p) - env.geometric_divergence(distance) - env.atmospheric_absorption( distance, frequencies=_QA_BANDS, temperature_c=_QA_TEMPERATURE, relative_humidity_percent=_QA_HUMIDITY, ) - env.ground_attenuation_alternative(distance, mean_height) ) scale = d_p / (_QA_RECEIVER[0] - _QA_SOURCE[0]) profile_x = ( 0.0, (120.0 - _QA_SOURCE[0]) * scale, (185.0 - _QA_SOURCE[0]) * scale, d_p, ) profile_z = (0.0, 0.0, 10.0, 10.0) return { "T01": general(env.GroundFactors(source=0.0, middle=0.0, receiver=0.0), d_flat), "T02": general(env.GroundFactors(source=0.5, middle=0.5, receiver=0.5), d_flat), "T03": general(env.GroundFactors(source=1.0, middle=1.0, receiver=1.0), d_flat), "T04": general( env.region_ground_factors( segments, (0.2, 0.5, 0.9), _QA_SOURCE[2], _QA_RECEIVER[2] ), d_flat, ), "T05": alternative( env.mean_path_height( (0.0, d_p), (0.0, 0.0), _QA_SOURCE[2], _QA_RECEIVER[2] ), d_flat, ), "T06": general( env.region_ground_factors( segments, (0.9, 0.5, 0.2), _QA_SOURCE[2], _QA_RECEIVER[2] ), d_sloped, ), "T07": alternative( env.mean_path_height( profile_x, profile_z, _QA_SOURCE[2], _QA_RECEIVER[2], distance=d_sloped, ), d_sloped, ), } def generate_iso17534_qa_cases(output_dir: str) -> None: """The seven quality-assurance cases ISO 9613-2 can answer on its own.""" print("Generating iso17534_qa_cases...") levels = _qa_levels() _fig, (ax, ax2) = plt.subplots( 1, 2, figsize=(11.6, 5.8), gridspec_kw={"width_ratios": [1.15, 1.0]} ) ground = ( ("T01", "reflecting ground, $G$ = 0", COLOR_PRIMARY, "-"), ("T02", "mixed ground, $G$ = 0.5", COLOR_TERTIARY, "--"), ("T03", "porous ground, $G$ = 1", COLOR_SECONDARY, "-."), ) for case, label, colour, style in ground: ax.semilogx(_QA_BANDS, levels[case], style, color=colour, lw=1.9, label=label) ax.semilogx( _QA_BANDS, _QA_PRINTED[case], "none", color=colour, marker="o", ms=5, markerfacecolor="none", ) ax.set_xlabel(LABEL_FREQ_HZ) ax.set_ylabel("Level at the receiver (dB)") ax.set_title("The Same Path Over Three Grounds", pad=10) ax.set_ylim(19.5, 46.0) format_frequency_axis(ax, language=_LANG) ax.grid(color=COLOR_GRID, linestyle="--", alpha=0.5, which="both") ax.set_axisbelow(True) ax.legend(loc="lower left", fontsize=8.5) ax.text( 0.985, 0.965, "93 dB in every band, 194.16 m out, 1 m up and 4 m down;\n" "rings: the levels the document prints", transform=ax.transAxes, va="top", ha="right", fontsize=8.5, color=COLOR_FG, bbox={ "boxstyle": "round,pad=0.32", "facecolor": COLOR_PANEL, "edgecolor": COLOR_GRID, }, ) cases = tuple(_QA_PRINTED) worst = [ float(np.max(np.abs(np.array(_QA_PRINTED[case]) - levels[case]))) for case in cases ] positions = np.arange(len(cases), dtype=float) ax2.bar( positions, worst, width=0.6, color=theme_fill(COLOR_PRIMARY, ax2), edgecolor=COLOR_PRIMARY, linewidth=1.2, zorder=3, ) ax2.axhline( _QA_ENVELOPE, color=COLOR_SECONDARY, linestyle="--", linewidth=1.6, label="the envelope the document declares: 0.05 dB", ) for x, value in zip(positions, worst, strict=True): ax2.text( x, value + 0.0015, f"{value:.3f}", ha="center", va="bottom", fontsize=8, color=COLOR_FG, zorder=4, ) ax2.set_xticks(positions) ax2.set_xticklabels(cases, fontsize=9) ax2.set_ylim(0.0, 0.062) ax2.set_ylabel("Worst band deviation (dB)") ax2.set_title("Every Case, Against Its Printed Table", pad=10) ax2.grid(axis="y", color=COLOR_GRID, linestyle="--", alpha=0.5) ax2.set_axisbelow(True) ax2.legend(loc="upper left", fontsize=8.5) plt.tight_layout() save_figure(output_dir, "iso17534_qa_cases.svg") plt.close() def generate_road_device_ratings(output_dir: str) -> None: """EN 1793: the spectrum that weights a road device, and the two ratings.""" print("Generating road_device_ratings.png...") from phonometry import environment bands = np.asarray(environment.TRAFFIC_NOISE_BANDS_HZ) spectrum = np.asarray(environment.NORMALIZED_TRAFFIC_NOISE_SPECTRUM_DB) x = np.arange(len(bands)) # Two devices of each kind, with the per-band performance a maker of that # kind declares: a cassette with mineral wool behind a perforated face, # and a plain concrete panel that reflects almost everything. absorptive = np.array( [ 0.15, 0.25, 0.40, 0.60, 0.80, 0.95, 0.98, 0.95, 0.92, 0.90, 0.88, 0.85, 0.82, 0.80, 0.78, 0.75, 0.72, 0.70, ] ) reflective = np.full(len(bands), 0.05) concrete = np.array( [ 30.0, 31.0, 33.0, 35.0, 37.0, 39.0, 41.0, 42.0, 44.0, 45.0, 46.0, 47.0, 48.0, 49.0, 50.0, 51.0, 52.0, 53.0, ] ) cassette = np.array( [ 21.0, 22.0, 23.0, 24.0, 25.0, 26.0, 27.0, 28.0, 29.0, 30.0, 31.0, 31.0, 32.0, 32.0, 33.0, 33.0, 34.0, 34.0, ] ) _fig, axes = plt.subplots(1, 3, figsize=(15.5, 5.4)) axes[0].bar( x, spectrum, color=COLOR_PRIMARY, edgecolor=COLOR_FG, linewidth=0.6, zorder=3, label="road, EN 1793-3", ) axes[0].plot( x, np.asarray(environment.NORMALIZED_RAILWAY_NOISE_SPECTRUM_DB), marker="o", markersize=4.5, color=COLOR_SECONDARY, linewidth=2.0, zorder=4, label="railway, EN 16272-3-1", ) axes[0].legend(loc="lower center", fontsize=9) axes[0].set_title("The weighting: one grid, two spectra") axes[0].set_ylabel("$L_i$ [dB]") axes[0].annotate( "the peak carries the rating", xy=(10, spectrum[10]), xytext=(4.6, spectrum[10] + 5.0), fontsize=10, color=COLOR_FG, arrowprops={"arrowstyle": "->", "color": COLOR_FG, "lw": 1.2}, bbox={ "boxstyle": "round,pad=0.5", "facecolor": COLOR_PANEL, "edgecolor": COLOR_GRID, }, ) for values, colour, label in ( (absorptive, COLOR_PRIMARY, "absorptive cassette"), (reflective, COLOR_SECONDARY, "concrete panel"), ): rating = environment.sound_absorption_rating(values) axes[1].plot( x, values, marker="o", markersize=4.5, color=colour, linewidth=2.0, label=f"{label}: $DL_\\alpha$ = {rating.reported} dB ({rating.category})", ) axes[1].set_title("EN 1793-1: what is not sent back") axes[1].set_ylabel(r"$\alpha_\mathrm{S}$") axes[1].set_ylim(0.0, 1.28) for values, colour, label in ( (concrete, COLOR_PRIMARY, "concrete panel"), (cassette, COLOR_SECONDARY, "metal cassette"), ): rating = environment.airborne_insulation_rating(values) axes[2].plot( x, values, marker="o", markersize=4.5, color=colour, linewidth=2.0, label=f"{label}: $DL_R$ = {rating.reported} dB ({rating.category})", ) axes[2].set_title("EN 1793-2: what is not let through") axes[2].set_ylabel("$R$ [dB]") for ax in axes: ax.set_xlabel("1/3-octave band centre frequency [Hz]") ax.set_xticks(x[::3]) ax.set_xticklabels([f"{b:g}" for b in bands[::3]]) ax.grid(axis="y", color=COLOR_GRID, linestyle="--", alpha=0.5, zorder=0) ax.set_axisbelow(True) axes[1].legend(loc="upper right", fontsize=9) axes[2].legend(loc="upper left", fontsize=9) plt.tight_layout() save_figure(output_dir, "road_device_ratings.png") plt.close() # --------------------------------------------------------------------------- # # EN 1793-5: the sound reflection of a barrier measured where it stands # --------------------------------------------------------------------------- # #: EN 1793-5:2016 Table B.1, printed folio 53: the index of twelve grid #: positions in front of a 4 m absorptive barrier, one row per band from #: 100 Hz to 5 kHz. The guide types the same table in. _EN1793_5_TABLE_B1: tuple[tuple[float, ...], ...] = ( (0.59, 0.62, 0.57, 0.55, 0.58, 0.59, 0.57, 0.57, 0.51, 0.61, 0.61, 0.62), (0.60, 0.62, 0.58, 0.54, 0.57, 0.58, 0.58, 0.58, 0.51, 0.60, 0.59, 0.61), (0.63, 0.65, 0.60, 0.55, 0.57, 0.59, 0.60, 0.60, 0.53, 0.60, 0.57, 0.60), (0.38, 0.42, 0.31, 0.37, 0.37, 0.35, 0.37, 0.39, 0.31, 0.36, 0.31, 0.32), (0.43, 0.47, 0.35, 0.39, 0.39, 0.36, 0.42, 0.43, 0.35, 0.38, 0.34, 0.36), (0.43, 0.45, 0.34, 0.37, 0.37, 0.34, 0.37, 0.37, 0.33, 0.33, 0.33, 0.33), (0.34, 0.33, 0.26, 0.28, 0.30, 0.27, 0.22, 0.24, 0.22, 0.21, 0.25, 0.23), (0.15, 0.15, 0.12, 0.13, 0.15, 0.15, 0.07, 0.08, 0.08, 0.11, 0.12, 0.12), (0.05, 0.04, 0.04, 0.07, 0.05, 0.06, 0.06, 0.04, 0.04, 0.09, 0.05, 0.06), (0.07, 0.07, 0.06, 0.13, 0.08, 0.07, 0.17, 0.11, 0.09, 0.11, 0.09, 0.07), (0.11, 0.10, 0.09, 0.13, 0.11, 0.08, 0.17, 0.16, 0.10, 0.08, 0.07, 0.04), (0.11, 0.13, 0.10, 0.07, 0.11, 0.08, 0.10, 0.13, 0.09, 0.10, 0.09, 0.07), (0.39, 0.53, 0.16, 0.37, 0.28, 0.21, 0.30, 0.23, 0.18, 0.30, 0.35, 0.29), (0.19, 0.28, 0.10, 0.20, 0.15, 0.12, 0.16, 0.15, 0.08, 0.13, 0.17, 0.22), (0.15, 0.23, 0.21, 0.14, 0.13, 0.17, 0.15, 0.15, 0.16, 0.12, 0.15, 0.10), (0.31, 0.33, 0.27, 0.26, 0.23, 0.19, 0.18, 0.25, 0.18, 0.16, 0.23, 0.21), (0.39, 0.27, 0.22, 0.23, 0.26, 0.21, 0.28, 0.22, 0.18, 0.28, 0.21, 0.24), (0.55, 0.43, 0.25, 0.52, 0.53, 0.53, 0.40, 0.43, 0.23, 0.46, 0.36, 0.45), ) #: Speed of sound of the guide's synthetic measurement, at 20 degC. _BARRIER_SPEED_M_S = 343.2 def _barrier_reflection_records() -> tuple[NDArray[np.float64], NDArray[np.float64]]: """The guide's nine in-front and free-field records, 48 kHz, 100 ms. A loudspeaker pulse at 2,5 kHz; a reflection of 0,35 of the incident amplitude with its top end smoothed; the free-field records taken with the grid 3 microseconds further away, which the subtraction undoes. """ from phonometry import environment fs = 48000.0 t = np.arange(4800) / fs def pulse(delay_s: float) -> NDArray[np.float64]: tau = t - delay_s return np.exp(-0.5 * (tau / 60e-6) ** 2) * np.cos(2 * np.pi * 2500.0 * tau) smooth = np.hanning(9) / np.hanning(9).sum() free = np.empty((9, t.size)) front = np.empty((9, t.size)) c = _BARRIER_SPEED_M_S for k, (direct_m, reflected_m) in enumerate(environment.reflection_grid_paths_m()): free[k] = pulse(0.01 + direct_m / c + 3e-6) / direct_m reflection = np.convolve(pulse(0.01 + reflected_m / c), smooth, mode="same") front[k] = ( pulse(0.01 + direct_m / c) / direct_m + 0.35 * reflection / reflected_m ) return front, free def generate_barrier_reflection_index(output_dir: str) -> None: """EN 1793-5 Annex B: twelve grid positions, their average and DL_RI.""" print("Generating barrier_reflection_index...") from phonometry import environment result = environment.reflection_index_from_positions( np.asarray(_EN1793_5_TABLE_B1).T ) _fig, ax = plt.subplots(figsize=(10, 6.2)) result.plot(ax=ax, language=_LANG) plt.tight_layout() save_figure(output_dir, "barrier_reflection_index.svg") plt.close() def generate_barrier_reflection_uncertainty(output_dir: str) -> None: """EN 1793-5 A.2 and B.5: the expanded uncertainty of the Annex B index.""" print("Generating barrier_reflection_uncertainty...") from phonometry import environment result = environment.reflection_index_expanded_uncertainty() _fig, ax = plt.subplots(figsize=(10, 6.2)) result.plot(ax=ax, language=_LANG) plt.tight_layout() save_figure(output_dir, "barrier_reflection_uncertainty.svg") plt.close() def generate_barrier_direct_sound_subtraction(output_dir: str) -> None: """EN 1793-5 5.5.4: the direct sound taken out of microphone 5's record.""" print("Generating barrier_direct_sound_subtraction...") from phonometry import environment front, free = _barrier_reflection_records() result = environment.subtract_direct_sound(front[4], free[4], 48000.0) _fig, ax = plt.subplots(figsize=(10, 6.2)) result.plot(ax=ax, language=_LANG) plt.tight_layout() save_figure(output_dir, "barrier_direct_sound_subtraction.svg") plt.close() def generate_barrier_reflection_limit(output_dir: str) -> None: """EN 1793-5 5.5.7: how far down each microphone reaches on a 3,5 m barrier.""" print("Generating barrier_reflection_limit...") from phonometry import environment result = environment.reflection_low_frequency_limit( 3.5, speed_of_sound=_BARRIER_SPEED_M_S ) _fig, ax = plt.subplots(figsize=(10, 6.2)) result.plot(ax=ax, language=_LANG) plt.tight_layout() save_figure(output_dir, "barrier_reflection_limit.svg") plt.close() def _qa_example_differences() -> tuple[float, ...]: """The 25 level differences of the example of ISO 17534-1 C.4, in dB. Read from the shared oracle the tests and the conformance report read, so the figure cannot drift from the rows that pin it. """ import sys from pathlib import Path # parents[2] is the repository root from scripts/figures/.py. tests = str(Path(__file__).resolve().parents[2] / "tests") if tests not in sys.path: sys.path.insert(0, tests) import reference_data as ref return tuple(float(value) for value in ref.ISO17534_1_EXAMPLE_DIFFERENCES_DB) #: ISO/TR 17534-3:2015, Table 6 (T03, porous ground), printed folio 9 (PDF #: page 15): the row L_A, the A-weighted level at the receiver in each octave #: band from 63 Hz to 8 kHz, dB. Footnote a puts the +/-0,05 dB of the #: certified results on this row, and the TRC form of ISO 17534-1 (Tables B.1 #: and B.2) lists A-weighted results. _QA_T03_LA = (13.70, 16.38, 17.73, 23.83, 33.27, 35.69, 32.79, 20.26) #: The same row, its total over the eight bands, dB. _QA_T03_LA_TOTAL = 39.14 #: The A-weighting every spectral table of ISO/TR 17534-3 prints in its own #: row, dB, so the A-weighted levels are formed as the document forms them. _QA_A_WEIGHTING = np.array([-26.2, -16.1, -8.6, -3.2, 0.0, 1.2, 1.0, -1.1]) #: The row labels of a TRC form over the eight octaves and their total. _QA_TRC_LABELS = ( "63 Hz", "125 Hz", "250 Hz", "500 Hz", "1 kHz", "2 kHz", "4 kHz", "8 kHz", "Total", ) def generate_software_quality_quantiles(output_dir: str) -> None: """ISO 17534-1 C.4: the 25 level differences of the example, by rank.""" print("Generating software_quality_quantiles...") from phonometry import environment result = environment.level_difference_quantiles(_qa_example_differences()) _fig, ax = plt.subplots(figsize=(10, 5.6)) result.plot(ax, language=_LANG) plt.tight_layout() save_figure(output_dir, "software_quality_quantiles.svg") plt.close() def _qa_trc_rows(levels: NDArray[np.float64]) -> NDArray[np.float64]: """The eight A-weighted band levels of a case and their total, dB.""" weighted = levels + _QA_A_WEIGHTING total = 10.0 * np.log10(np.sum(10.0 ** (weighted / 10.0))) return np.concatenate((weighted, [total])) def generate_software_quality_trc(output_dir: str) -> None: """ISO 17534-1 7.1: this library's TRC form for ISO/TR 17534-3 case T03. The rows are those of the form: the A-weighted level in each octave band and their total, against the row L_A of Table 6, which footnote a certifies to +/-0,05 dB. Left, the library as it is: every band and the total of T03 (porous ground) inside. Right, the same calculation with the air absorption read at the nominal band centres instead of the exact base-10 midbands ISO 9613-2 Table 2 is computed at: 8 kHz is read at 8000 Hz instead of 7943 Hz, which alone moves that band 0,20 dB off its certified result, 0,15 dB below the lower limit. The kind of implementation detail the form exists to catch. """ print("Generating software_quality_trc...") from phonometry import environment printed = np.array((*_QA_T03_LA, _QA_T03_LA_TOTAL)) tol = environment.CERTIFIED_RESULT_TOLERANCE_DB exact = _qa_levels()["T03"] d_p = math.hypot(_QA_RECEIVER[0] - _QA_SOURCE[0], _QA_RECEIVER[1] - _QA_SOURCE[1]) d = math.hypot(d_p, _QA_RECEIVER[2] - _QA_SOURCE[2]) # Swap the exact-midband absorption for one read at the nominal centres. nominal = ( exact + environment.atmospheric_absorption( d, frequencies=_QA_BANDS, temperature_c=_QA_TEMPERATURE, relative_humidity_percent=_QA_HUMIDITY, ) - d * environment.air_attenuation( _QA_BANDS, temperature_c=_QA_TEMPERATURE, relative_humidity_percent=_QA_HUMIDITY, ) ) _fig, axes = plt.subplots(1, 2, figsize=(13.0, 5.4), sharey=False) notes = ( "T03 as this library computes it:\nthe air at the exact midbands", "The same, with the air read at\nthe nominal band centres", ) for ax, levels, note in zip(axes, (exact, nominal), notes, strict=True): verdict = environment.verify_calculation_results( _qa_trc_rows(np.asarray(levels)), printed - tol, printed + tol, labels=_QA_TRC_LABELS, ) verdict.plot(ax, language=_LANG) ax.text( 0.02, 0.03, note, transform=ax.transAxes, ha="left", va="bottom", fontsize=9, color=COLOR_FG, bbox={ "boxstyle": "round,pad=0.3", "facecolor": COLOR_PANEL, "edgecolor": COLOR_GRID, }, ) plt.tight_layout() save_figure(output_dir, "software_quality_trc.svg") plt.close() def generate_software_quality_round_robin(output_dir: str) -> None: """ISO 17534-1 4.5.2 and A.3: four programs at 400 receivers. A synthetic round robin in the shape of the TestCity example of A.3: 400 receivers and four participants, each program off the common level by a spread that differs from receiver to receiver, so a few receivers disagree by far more than most. Fixed seed. """ print("Generating software_quality_round_robin...") from phonometry import environment rng = np.random.default_rng(17534) receivers, programs = 400, 4 common = rng.uniform(45.0, 70.0, receivers) spread = 0.15 + 0.6 * rng.gamma(1.5, 0.4, receivers) levels = common[:, None] + spread[:, None] * rng.standard_normal( (receivers, programs) ) result = environment.round_robin_precision(levels) _fig, ax = plt.subplots(figsize=(10, 5.4)) result.plot(ax, language=_LANG) plt.tight_layout() save_figure(output_dir, "software_quality_round_robin.svg") plt.close() # --------------------------------------------------------------------------- # ISO 3095 rolling stock noise, on a track judged by EN 15610 and EN 15461. # The scenes are the ones the rolling-stock guide's code blocks build, seeded, # so every figure and every printed number are one measurement. # --------------------------------------------------------------------------- #: The one-third octave bands the track decay rates and the pass-by spectrum #: of the guide are given in, 100 Hz to 5 kHz. _ROLLING_STOCK_BANDS_HZ = ( 100.0, 125.0, 160.0, 200.0, 250.0, 315.0, 400.0, 500.0, 630.0, 800.0, 1000.0, 1250.0, 1600.0, 2000.0, 2500.0, 3150.0, 4000.0, 5000.0, ) # fmt: skip def _rolling_stock_pass_by() -> PassByMeasurement: """A 100 m unit at 80 km/h past a microphone at 7,5 m, as a line source.""" from phonometry import environment fs = 16000 length_m, speed_kmh, distance_m = 100.0, 80.0, 7.5 tp = environment.pass_by_time(length_m, speed_kmh=speed_kmh) t = np.arange(int(14.0 * fs)) / fs front_s = 4.0 x_front = speed_kmh / 3.6 * (t - front_s) angle = np.arctan(x_front / distance_m) - np.arctan( (x_front - length_m) / distance_m ) rng = np.random.default_rng(3095) p = 0.25 * np.sqrt(angle / np.pi + 1e-4) * rng.standard_normal(t.size) return environment.pass_by_measurement(p, fs, start_s=front_s, end_s=front_s + tp) def _rolling_stock_track() -> tuple[ReferenceTrackCheck, SmallRoughnessDeviation]: """The reference track of the guide: two rails, two decay rates, Annex C.""" from phonometry import environment limit = environment.REFERENCE_TRACK_ROUGHNESS_LIMIT_DB x = np.arange(0.0, 20.0, 1.0e-3) def rail(offsets_db: dict[float, float], seed: int) -> NDArray[np.float64]: rng = np.random.default_rng(seed) r = np.zeros_like(x) for wavelength, level in limit.items(): target = level + offsets_db.get(wavelength, -3.0) k = 10.0 ** np.linspace(-0.045, 0.045, 10) / wavelength amplitude = np.sqrt(2.0 * 10.0 ** (target / 10.0) / k.size) for kk in k: r += amplitude * np.cos( 2.0 * np.pi * kk * x + rng.uniform(0.0, 2.0 * np.pi) ) return r left = rail({0.05: -1.0, 0.04: 2.0, 0.0315: 2.5, 0.025: 0.5}, seed=1) right = rail({0.04: 1.0, 0.0315: 1.5}, seed=2) left[7300] += 25.0 spectra = [ environment.acoustic_roughness_spectrum(r, sample_spacing_m=1.0e-3) for r in (left, right) ] bands = list(_ROLLING_STOCK_BANDS_HZ) vertical = [9.0, 8.0, 6.0, 4.0, 3.0, 3.5, 7.0, 8.0, 7.0, 3.0, 1.2, 0.9, 0.9, 1.0, 1.1, 1.3, 1.5, 1.8] # fmt: skip lateral = [6.0, 5.0, 4.0, 3.0, 3.0, 2.2, 1.2, 0.9, 0.7, 0.6, 0.5, 0.5, 0.6, 0.8, 0.9, 1.0, 1.2, 1.4] # fmt: skip x_hammer = environment.track_decay_excitation_positions(sleeper_spacing_m=0.6) def responses(rates_db_per_m: list[float]) -> NDArray[np.float64]: beta = np.asarray(rates_db_per_m) / (20.0 * np.log10(np.e)) return np.exp(-np.outer(x_hammer, beta)) decay = [ environment.track_decay_rate( responses(vertical), frequencies=bands, direction="vertical" ), environment.track_decay_rate( responses(lateral), frequencies=bands, direction="lateral" ), ] noise = [68.0, 69.5, 71.0, 72.5, 74.0, 76.0, 78.0, 80.5, 83.0, 85.5, 87.0, 87.5, 86.5, 84.5, 82.0, 79.0, 75.5, 72.0] # fmt: skip small = environment.check_small_roughness_deviations( environment.average_roughness_spectra(spectra), noise, frequencies=bands, speed_kmh=160.0, ) check = environment.check_reference_track( spectra, decay, speed_kmh=160.0, curve_radius_m=6000.0, track_gradient_ratio=0.002, small_deviations=small, ) return check, small #: ISO 3095 Table G.2: each input's name in the two languages, its mean value #: correction and its standard uncertainty, dB. _TABLE_G2_ROWS: tuple[tuple[str, str, float, float], ...] = ( ("cal, reference", "calibrador, referencia", 0.0, 0.14), ("cal, long term", "calibrador, largo plazo", 0.0, 0.04), ("cal, supply voltage", "calibrador, alimentación", 0.0, 0.06), ("cal, distortion factor", "calibrador, distorsión", 0.105, 0.06), ("slm, direction", "sonómetro, dirección", 0.0, 0.25), ("slm, frequency", "sonómetro, frecuencia", 0.0, 0.25), ("slm, level linearity", "sonómetro, linealidad", 0.0, 0.46), ("calibrator, meteorological", "calibrador, meteorología", 0.0, 0.14), ("slm, wind screen", "sonómetro, pantalla antiviento", 0.06, 0.03), ("tripod", "trípode", 0.0, 0.35), ("distance", "distancia", 0.0, 0.06), ("ground level", "nivel del terreno", 0.515, 0.30), ("rounding", "redondeo", 0.0, 0.29), ) def generate_rolling_stock_pass_by(output_dir: str) -> None: """ISO 3095 6.6.3: the level history of a pass-by and its interval Tp.""" print("Generating rolling_stock_pass_by...") _fig, ax = plt.subplots(figsize=(10, 6.2)) _rolling_stock_pass_by().plot(ax=ax, language=_LANG) plt.tight_layout() save_figure(output_dir, "rolling_stock_pass_by.svg") plt.close() def generate_rolling_stock_track_roughness(output_dir: str) -> None: """ISO 3095 6.2.5: the roughness of two rails against Figure 2.""" print("Generating rolling_stock_track_roughness...") check, _small = _rolling_stock_track() _fig, ax = plt.subplots(figsize=(10, 6.2)) check.plot(ax=ax, panel="roughness", language=_LANG) plt.tight_layout() save_figure(output_dir, "rolling_stock_track_roughness.svg") plt.close() def generate_rolling_stock_roughness_methods(output_dir: str) -> None: """EN 15610 7.4.2 and 7.4.3: Methods A and B on one 20 m record.""" print("Generating rolling_stock_roughness_methods...") from phonometry import environment limit = environment.REFERENCE_TRACK_ROUGHNESS_LIMIT_DB # Every band 3 dB under the limit, with the 0,5 m and 2,5 mm bands the # limit does not cover carried on along its slope. levels = {w: v - 3.0 for w, v in limit.items()} levels[0.5] = 16.1 levels[0.0025] = -14.6 x = np.arange(0.0, 20.0, 1.0e-3) rng = np.random.default_rng(15610) record = np.zeros_like(x) for wavelength, level in levels.items(): k = 10.0 ** np.linspace(-0.045, 0.045, 10) / wavelength amplitude = np.sqrt(2.0 * 10.0 ** (level / 10.0) / k.size) for kk in k: record += amplitude * np.cos( 2.0 * np.pi * kk * x + rng.uniform(0.0, 2.0 * np.pi) ) fourier = environment.acoustic_roughness_spectrum(record, sample_spacing_m=1.0e-3) filtered = environment.filtered_roughness_spectrum(record, sample_spacing_m=1.0e-3) spanish = _LANG == "es" _fig, ax = plt.subplots(figsize=(10, 6.2)) fourier.plot( ax=ax, language=_LANG, label="Método A (Fourier, segmentos de 1 m)" if spanish else "Method A (Fourier, 1 m segments)", ) filtered.plot( ax=ax, limit_db=limit, language=_LANG, color=COLOR_TERTIARY, marker="s", label="Método B (filtros, 2 m descartados en cada extremo)" if spanish else "Method B (filters, 2 m discarded at either end)", ) ax.set_title( "Métodos A y B de la EN 15610 sobre un mismo registro de 20 m" if spanish else "EN 15610 Methods A and B on one 20 m record" ) plt.tight_layout() save_figure(output_dir, "rolling_stock_roughness_methods.svg") plt.close() def generate_rolling_stock_track_decay(output_dir: str) -> None: """ISO 3095 6.2.6: the vertical and lateral decay rates against Figure 3.""" print("Generating rolling_stock_track_decay...") check, _small = _rolling_stock_track() _fig, ax = plt.subplots(figsize=(10, 6.2)) check.plot(ax=ax, panel="decay", language=_LANG) plt.tight_layout() save_figure(output_dir, "rolling_stock_track_decay.svg") plt.close() def generate_rolling_stock_small_deviation(output_dir: str) -> None: """ISO 3095 Annex C: the measured and revised pass-by spectra at 160 km/h.""" print("Generating rolling_stock_small_deviation...") _check, small = _rolling_stock_track() _fig, ax = plt.subplots(figsize=(10, 6.2)) small.plot(ax=ax, language=_LANG) plt.tight_layout() save_figure(output_dir, "rolling_stock_small_deviation.svg") plt.close() def generate_rolling_stock_uncertainty(output_dir: str) -> None: """ISO 3095 Annex G: the budget of Table G.2 drawn as Figure G.1.""" print("Generating rolling_stock_uncertainty...") from phonometry import environment, metrology budget = environment.pass_by_uncertainty( 55.0, [ metrology.Quantity( value=value, uncertainty=u, name=spanish if _LANG == "es" else english ) for english, spanish, value, u in _TABLE_G2_ROWS ], ) _fig, ax = plt.subplots(figsize=(10, 6.4)) budget.plot(ax=ax, language=_LANG) plt.tight_layout() save_figure(output_dir, "rolling_stock_uncertainty.svg") plt.close()