Interactive 2D wave optics simulator. Turn any image into a refractive scene, add sources, watch waves refract, diffract and interfere. Probes, intensity maps, video export.
C#
A logarithmic value axis for intensity probe graphs
Alexander Graeff3742a4a9f1b
diff --git a/CLAUDE.md b/CLAUDE.mdindex 78756da..91629c0 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -149,7 +149,8 @@ FrameStore: native memory up to the budget, the rest in a temp file (%LOCALAPPDAthrough `IMovable` with the delta limited so none leaves the canvas (the formation holds); Escape during a drag putsthings back; Remove, Duplicate and Enabled act on the whole selection when their target is in it; the lever, gripsand point handles belong to the current item alone. Probe graph boxes follow their probe while attached, resize by a grip, keep their text- size; an amplitude axis is symmetric about zero.+ size; an amplitude axis is symmetric about zero; an intensity graph's value axis can be logarithmic (2026-10-20,+ Jeroen's point 8: `Decades` below the fitted top, zeros on the bottom line, powers-of-ten ticks; the field stays linear).- **Colour schemes** are stop lists in `.wdscheme` XML, shipped ones embedded, user ones in`%LOCALAPPDATA%\WaveDudeNext\ColorSchemes`, project ones in the `.wdproj`; an in-house picker edits stops;renaming a project scheme repoints its layers. **The scene image** is embedded and follows its file on disk;diff --git a/WaveDudeNext.WPF/Strings/Strings.DE.xaml b/WaveDudeNext.WPF/Strings/Strings.DE.xamlindex cffc894..53b10ab 100644--- a/WaveDudeNext.WPF/Strings/Strings.DE.xaml+++ b/WaveDudeNext.WPF/Strings/Strings.DE.xaml@@ -376,6 +376,10 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<s:String x:Key="Hint.Probe.YMin">Untere Grenze der Werteachse ohne automatische Skalierung.</s:String><s:String x:Key="Label.Probe.YMax">Wert Maximum</s:String><s:String x:Key="Hint.Probe.YMax">Obere Grenze der Werteachse ohne automatische Skalierung.</s:String>+ <s:String x:Key="Label.Probe.YScale">Werteachse</s:String>+ <s:String x:Key="Hint.Probe.YScale">Lineare oder logarithmische Werteachse; nur Intensitätssonden, das Feld ist immer linear.</s:String>+ <s:String x:Key="Label.Probe.Decades">Dekaden</s:String>+ <s:String x:Key="Hint.Probe.Decades">Dekaden, die eine logarithmische Werteachse unter ihrem oberen Ende zeigt; kleinere Werte, auch null, liegen auf der unteren Linie.</s:String><s:String x:Key="Label.Probe.Window">Fenster</s:String><s:String x:Key="Hint.Probe.Window">Breite des gleitenden Schrittfensters, in Schritten.</s:String><s:String x:Key="Label.Probe.StartAfter">Start nach Schritt</s:String>@@ -499,6 +503,8 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<s:String x:Key="Enum.ProbeBoxSize.Custom">Eigene</s:String><s:String x:Key="Enum.ProbeScaleMode.Running">Gleitend</s:String><s:String x:Key="Enum.ProbeScaleMode.Full">Ganzer Lauf</s:String>+ <s:String x:Key="Enum.ProbeValueScale.Linear">Linear</s:String>+ <s:String x:Key="Enum.ProbeValueScale.Logarithmic">Logarithmisch</s:String><s:String x:Key="Enum.SceneMode.Canvas">Leinwand</s:String><s:String x:Key="Enum.SceneMode.Image">Bild</s:String><s:String x:Key="Enum.EdgeMode.Open">Offen</s:String>diff --git a/WaveDudeNext.WPF/Strings/Strings.EN.xaml b/WaveDudeNext.WPF/Strings/Strings.EN.xamlindex 001a033..5f3035a 100644--- a/WaveDudeNext.WPF/Strings/Strings.EN.xaml+++ b/WaveDudeNext.WPF/Strings/Strings.EN.xaml@@ -378,6 +378,10 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<s:String x:Key="Hint.Probe.YMin">Lower bound of the value axis when it is not auto-scaled.</s:String><s:String x:Key="Label.Probe.YMax">Value maximum</s:String><s:String x:Key="Hint.Probe.YMax">Upper bound of the value axis when it is not auto-scaled.</s:String>+ <s:String x:Key="Label.Probe.YScale">Value axis</s:String>+ <s:String x:Key="Hint.Probe.YScale">A linear or a logarithmic value axis; intensity probes only, the field is always linear.</s:String>+ <s:String x:Key="Label.Probe.Decades">Decades</s:String>+ <s:String x:Key="Hint.Probe.Decades">Decades a logarithmic value axis spans below its top; smaller values, zero included, sit on the bottom line.</s:String><s:String x:Key="Label.Probe.Window">Window</s:String><s:String x:Key="Hint.Probe.Window">Width of the sliding step window, in steps.</s:String><s:String x:Key="Label.Probe.StartAfter">Start after step</s:String>@@ -501,6 +505,8 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<s:String x:Key="Enum.ProbeBoxSize.Custom">Custom</s:String><s:String x:Key="Enum.ProbeScaleMode.Running">Running</s:String><s:String x:Key="Enum.ProbeScaleMode.Full">Full</s:String>+ <s:String x:Key="Enum.ProbeValueScale.Linear">Linear</s:String>+ <s:String x:Key="Enum.ProbeValueScale.Logarithmic">Logarithmic</s:String><s:String x:Key="Enum.SceneMode.Canvas">Canvas</s:String><s:String x:Key="Enum.SceneMode.Image">Image</s:String><s:String x:Key="Enum.EdgeMode.Open">Open</s:String>diff --git a/WaveDudeNext.WPF/Strings/Strings.FR.xaml b/WaveDudeNext.WPF/Strings/Strings.FR.xamlindex 31cbf06..b275111 100644--- a/WaveDudeNext.WPF/Strings/Strings.FR.xaml+++ b/WaveDudeNext.WPF/Strings/Strings.FR.xaml@@ -376,6 +376,10 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<s:String x:Key="Hint.Probe.YMin">Borne inférieure de l'axe des valeurs sans échelle automatique.</s:String><s:String x:Key="Label.Probe.YMax">Valeur maximale</s:String><s:String x:Key="Hint.Probe.YMax">Borne supérieure de l'axe des valeurs sans échelle automatique.</s:String>+ <s:String x:Key="Label.Probe.YScale">Axe des valeurs</s:String>+ <s:String x:Key="Hint.Probe.YScale">Axe des valeurs linéaire ou logarithmique ; sondes d'intensité seulement, le champ est toujours linéaire.</s:String>+ <s:String x:Key="Label.Probe.Decades">Décades</s:String>+ <s:String x:Key="Hint.Probe.Decades">Décades couvertes par un axe logarithmique sous son sommet ; les valeurs plus petites, zéro compris, se posent sur la ligne du bas.</s:String><s:String x:Key="Label.Probe.Window">Fenêtre</s:String><s:String x:Key="Hint.Probe.Window">Largeur de la fenêtre glissante, en pas.</s:String><s:String x:Key="Label.Probe.StartAfter">Début après le pas</s:String>@@ -499,6 +503,8 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<s:String x:Key="Enum.ProbeBoxSize.Custom">Personnalisée</s:String><s:String x:Key="Enum.ProbeScaleMode.Running">Glissant</s:String><s:String x:Key="Enum.ProbeScaleMode.Full">Toute l'exécution</s:String>+ <s:String x:Key="Enum.ProbeValueScale.Linear">Linéaire</s:String>+ <s:String x:Key="Enum.ProbeValueScale.Logarithmic">Logarithmique</s:String><s:String x:Key="Enum.SceneMode.Canvas">Toile</s:String><s:String x:Key="Enum.SceneMode.Image">Image</s:String><s:String x:Key="Enum.EdgeMode.Open">Ouvert</s:String>diff --git a/WaveDudeNext.WPF/Strings/Strings.NL.xaml b/WaveDudeNext.WPF/Strings/Strings.NL.xamlindex dfedadb..a95156c 100644--- a/WaveDudeNext.WPF/Strings/Strings.NL.xaml+++ b/WaveDudeNext.WPF/Strings/Strings.NL.xaml@@ -376,6 +376,10 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<s:String x:Key="Hint.Probe.YMin">Ondergrens van de waardenas zonder automatische schaling.</s:String><s:String x:Key="Label.Probe.YMax">Maximumwaarde</s:String><s:String x:Key="Hint.Probe.YMax">Bovengrens van de waardenas zonder automatische schaling.</s:String>+ <s:String x:Key="Label.Probe.YScale">Waardenas</s:String>+ <s:String x:Key="Hint.Probe.YScale">Lineaire of logaritmische waardenas; alleen intensiteitssondes, het veld is altijd lineair.</s:String>+ <s:String x:Key="Label.Probe.Decades">Decaden</s:String>+ <s:String x:Key="Hint.Probe.Decades">Decaden die een logaritmische waardenas onder zijn bovenkant toont; kleinere waarden, nul inbegrepen, liggen op de onderste lijn.</s:String><s:String x:Key="Label.Probe.Window">Venster</s:String><s:String x:Key="Hint.Probe.Window">Breedte van het schuivende stappenvenster, in stappen.</s:String><s:String x:Key="Label.Probe.StartAfter">Start na stap</s:String>@@ -499,6 +503,8 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<s:String x:Key="Enum.ProbeBoxSize.Custom">Eigen maat</s:String><s:String x:Key="Enum.ProbeScaleMode.Running">Schuivend</s:String><s:String x:Key="Enum.ProbeScaleMode.Full">Hele run</s:String>+ <s:String x:Key="Enum.ProbeValueScale.Linear">Lineair</s:String>+ <s:String x:Key="Enum.ProbeValueScale.Logarithmic">Logaritmisch</s:String><s:String x:Key="Enum.SceneMode.Canvas">Canvas</s:String><s:String x:Key="Enum.SceneMode.Image">Afbeelding</s:String><s:String x:Key="Enum.EdgeMode.Open">Open</s:String>diff --git a/WaveDudeNext.WPF/Views/ProbeView.xaml b/WaveDudeNext.WPF/Views/ProbeView.xamlindex b39a064..4842e7a 100644--- a/WaveDudeNext.WPF/Views/ProbeView.xaml+++ b/WaveDudeNext.WPF/Views/ProbeView.xaml@@ -49,6 +49,22 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or</DataTrigger></Style.Triggers></Style>+ <!-- a logarithmic value axis only on the intensity layer (the field's amplitude changes sign), the decades only with it -->+ <Style x:Key="IntensityOnlyCombo" TargetType="{x:Type ComboBox}" BasedOn="{StaticResource EnumComboBox}">+ <Style.Triggers>+ <DataTrigger Binding="{Binding Layer}" Value="Field">+ <Setter Property="IsEnabled" Value="False" />+ </DataTrigger>+ </Style.Triggers>+ </Style>+ <Style x:Key="LogarithmicOnly" TargetType="{x:Type controls:NumberBox}" BasedOn="{StaticResource {x:Type controls:NumberBox}}">+ <Setter Property="IsEnabled" Value="False" />+ <Style.Triggers>+ <DataTrigger Binding="{Binding IsLogarithmic}" Value="True">+ <Setter Property="IsEnabled" Value="True" />+ </DataTrigger>+ </Style.Triggers>+ </Style><!-- the box width and height only apply to a custom box size (set by dragging the box's corner, too) --><Style x:Key="CustomSizeOnly" TargetType="{x:Type controls:NumberBox}" BasedOn="{StaticResource {x:Type controls:NumberBox}}"><Setter Property="IsEnabled" Value="False" />@@ -138,6 +154,13 @@ version. It is distributed WITHOUT ANY WARRANTY. See the LICENSE.md file or<CheckBox controls:FormPanel.FullWidth="True" Content="{meta:Label model:Probe.AutoScaleY}"IsChecked="{Binding AutoScaleY}" ToolTip="{meta:Hint model:Probe.AutoScaleY}" />+ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Probe.YScale}" />+ <ComboBox Style="{StaticResource IntensityOnlyCombo}" ItemsSource="{meta:EnumValues model:ProbeValueScale}"+ SelectedItem="{Binding YScale}" ToolTip="{meta:Hint model:Probe.YScale}" AutomationProperties.AutomationId="ProbeYScale" />++ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Probe.Decades}" />+ <controls:NumberBox Style="{StaticResource LogarithmicOnly}" Text="{Binding Decades}" Minimum="1" Maximum="12" ToolTip="{meta:Hint model:Probe.Decades}" />+<TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Probe.YMin}" /><controls:NumberBox Text="{Binding YMin}" Increment="0.1" ToolTip="{meta:Hint model:Probe.YMin}" />diff --git a/WaveDudeNext/Model/Probe.cs b/WaveDudeNext/Model/Probe.csindex 05f3e43..ea26a15 100644--- a/WaveDudeNext/Model/Probe.cs+++ b/WaveDudeNext/Model/Probe.cs@@ -76,6 +76,15 @@ public enum ProbeScaleModeFull,}+/// <summary>How the value axis of a probe graph maps values to heights.</summary>+public enum ProbeValueScale+{+ /// <summary>Equal steps in value are equal steps in height.</summary>+ Linear,+ /// <summary>Equal factors in value are equal steps in height, over <see cref="Probe.Decades"/> decades; intensity probes only.</summary>+ Logarithmic,+}+/// <summary>/// A measurement point or line on the canvas and the graph that shows its values. Positions are/// canvas pixels with the origin at the top left.@@ -98,6 +107,12 @@ public sealed class Probe : ObservableObject, IMovablepublic const int MinBoxHeight = 30;/// <summary>Largest accepted <see cref="BoxWidth"/> and <see cref="BoxHeight"/>.</summary>public const int MaxBoxSide = 4096;+ /// <summary>Default <see cref="Decades"/>.</summary>+ public const int DefaultDecades = 6;+ /// <summary>Smallest accepted <see cref="Decades"/>.</summary>+ public const int MinDecades = 1;+ /// <summary>Largest accepted <see cref="Decades"/>.</summary>+ public const int MaxDecades = 12;private string _name = "";private bool _active = true;@@ -118,6 +133,8 @@ public sealed class Probe : ObservableObject, IMovableprivate bool _autoScaleY = true;private double _yMin = -1.0;private double _yMax = 1.0;+ private ProbeValueScale _yScale = ProbeValueScale.Linear;+ private int _decades = DefaultDecades;private int _window = DefaultWindow;private int _startAfter;@@ -156,6 +173,11 @@ public sealed class Probe : ObservableObject, IMovable{// the measurement follows the layer at once, so the editor never shows an impossible pairMeasurement = MeasurementsFor(value).Contains(Measurement) ? Measurement : MeasurementsFor(value)[0];+ if (value == ProbeLayer.Field)+ {+ YScale = ProbeValueScale.Linear;+ }+ OnPropertyChanged(nameof(IsLogarithmic));}}}@@ -375,6 +397,49 @@ public sealed class Probe : ObservableObject, IMovableset => SetProperty(ref _yMax, value);}+ /// <summary>+ /// A linear or a logarithmic value axis; logarithmic only on the intensity layer (the field's amplitude changes+ /// sign): setting the layer to the field coerces it, <see cref="Normalize"/> re-checks it. A graph setting, not+ /// a measurement: the recordings and the CSV export keep the plain values.+ /// </summary>+ [XmlAttribute]+ [DefaultValue(ProbeValueScale.Linear)]+ [Category("Axes")]+ [DisplayName("Value axis")]+ [Description("A linear or a logarithmic value axis; intensity probes only, the field is always linear.")]+ public ProbeValueScale YScale+ {+ get => _yScale;+ set+ {+ if (SetProperty(ref _yScale, value))+ {+ OnPropertyChanged(nameof(IsLogarithmic));+ }+ }+ }++ /// <summary>+ /// Decades a logarithmic value axis spans below its top (auto-scaled or <see cref="YMax"/>); smaller values,+ /// zero included, are drawn on the bottom line. The bottom is <see cref="YMin"/> instead when the axis is+ /// fixed and <see cref="YMin"/> is positive. Clamped to <see cref="MinDecades"/>..<see cref="MaxDecades"/>.+ /// </summary>+ [XmlAttribute]+ [DefaultValue(DefaultDecades)]+ [Category("Axes")]+ [DisplayName("Decades")]+ [Description("Decades a logarithmic value axis spans below its top; smaller values, zero included, sit on the bottom line.")]+ public int Decades+ {+ get => _decades;+ set => SetProperty(ref _decades, value);+ }++ /// <summary>Whether the graph's value axis is logarithmic: <see cref="YScale"/> says so and the probe is on the intensity layer. Raises its change with either.</summary>+ [XmlIgnore]+ [Browsable(false)]+ public bool IsLogarithmic => YScale == ProbeValueScale.Logarithmic && Layer == ProbeLayer.Intensity;+/// <summary>Width of the sliding step window for <see cref="ProbeScaleMode.Running"/>, in steps.</summary>[XmlAttribute][DefaultValue(DefaultWindow)]@@ -443,8 +508,8 @@ public sealed class Probe : ObservableObject, IMovable/// <summary>/// Forces a consistent state: the field only allows <see cref="ProbeMeasurement.Amplitude"/>,- /// the intensity output never does; an empty or inverted Y range becomes -1..1; the window,- /// the custom box size and the start step are clamped.+ /// the intensity output never does; the field's value axis is linear; an empty or inverted Y range becomes+ /// -1..1; the window, the custom box size, the start step and the decades are clamped./// </summary>public void Normalize(){@@ -452,6 +517,7 @@ public sealed class Probe : ObservableObject, IMovableif (Layer == ProbeLayer.Field){Measurement = ProbeMeasurement.Amplitude;+ YScale = ProbeValueScale.Linear;}else if (Measurement == ProbeMeasurement.Amplitude){@@ -466,6 +532,7 @@ public sealed class Probe : ObservableObject, IMovableBoxWidth = Math.Clamp(BoxWidth, MinBoxWidth, MaxBoxSide);BoxHeight = Math.Clamp(BoxHeight, MinBoxHeight, MaxBoxSide);StartAfter = Math.Max(0, StartAfter);+ Decades = Math.Clamp(Decades, MinDecades, MaxDecades);}/// <summary>A copy with the same settings and no change subscribers.</summary>diff --git a/WaveDudeNext/Probes/ProbeGraph.cs b/WaveDudeNext/Probes/ProbeGraph.csindex d2c7aa1..3a4f915 100644--- a/WaveDudeNext/Probes/ProbeGraph.cs+++ b/WaveDudeNext/Probes/ProbeGraph.cs@@ -251,14 +251,15 @@ public static class ProbeGraph/// The axis ranges of a probe graph. For series graphs x is the step number (sample i sits at x = i + 1),/// spanning either the whole run or a running window; for profiles x is the distance along the line in/// canvas pixels. y comes from the probe's fixed range (falling back to -1..1 when it is empty or inverted)- /// or, with auto-scaling, from the visible data plus a small margin.+ /// or, with auto-scaling, from the visible data plus a small margin. A logarithmic axis+ /// (<see cref="Probe.IsLogarithmic"/>) gets a positive range, see <see cref="LogRange"/>./// </summary>/// <param name="probe">Selects kind, scale mode, fixed y range and auto-scaling.</param>/// <param name="data">The data shown; <c>default</c> yields the ranges of an empty graph.</param>/// <param name="totalSteps">Total steps of the run; the upper x limit of full-scale series graphs without auto-scaling.</param>/// <param name="xMin">Receives the lower x limit.</param>/// <param name="xMax">Receives the upper x limit, always greater than <paramref name="xMin"/>.</param>- /// <param name="yMin">Receives the lower y limit.</param>+ /// <param name="yMin">Receives the lower y limit; positive on a logarithmic axis.</param>/// <param name="yMax">Receives the upper y limit, always greater than <paramref name="yMin"/>.</param>public static void ComputeRanges(Probe probe, in ProbeGraphData data, int totalSteps, out double xMin, out double xMax, out double yMin, out double yMax){@@ -309,15 +310,22 @@ public static class ProbeGraphxMax = xMin + 1.0;}FixedRange(probe, out yMin, out yMax);+ float hi = 0f;+ bool fitted = false;if (probe.AutoScaleY && count > 0){int firstIndex = Math.Max(0, (int)Math.Floor(xMin) - 1);int lastIndex = Math.Min(count - 1, (int)Math.Ceiling(xMax));- if (Extent(data.Values!, firstIndex, lastIndex, out float lo, out float hi))+ if (Extent(data.Values!, firstIndex, lastIndex, out float lo, out hi)){+ fitted = true;AutoRange(probe, lo, hi, ref yMin, ref yMax);}}+ if (probe.IsLogarithmic)+ {+ LogRange(probe, fitted, hi, ref yMin, ref yMax);+ }}/// <summary>@@ -330,10 +338,17 @@ public static class ProbeGraphxMin = 0.0;xMax = data.Profile != null && data.ProfileLength > 0.0 ? data.ProfileLength : 1.0;FixedRange(probe, out yMin, out yMax);- if (probe.AutoScaleY && data.Profile is { } profile && Extent(profile, 0, profile.Length - 1, out float lo, out float hi))+ float hi = 0f;+ bool fitted = false;+ if (probe.AutoScaleY && data.Profile is { } profile && Extent(profile, 0, profile.Length - 1, out float lo, out hi)){+ fitted = true;AutoRange(probe, lo, hi, ref yMin, ref yMax);}+ if (probe.IsLogarithmic)+ {+ LogRange(probe, fitted, hi, ref yMin, ref yMax);+ }}/// <summary>The probe's fixed y range, or -1..1 when it is empty, inverted or NaN (written so a NaN limit also falls back).</summary>@@ -400,6 +415,127 @@ public static class ProbeGraph/// <summary>Room above the largest value (and below the smallest of a symmetric axis), as a fraction, so the curve does not touch the plot border.</summary>private const double Margin = 0.08;+ /// <summary>+ /// The range of a logarithmic value axis, from the linear one: auto-scaled with data above zero, the top is the+ /// largest value raised by 8 % of the axis height (<see cref="Margin"/> × the decades, in decades) and the+ /// bottom <see cref="Probe.Decades"/> decades below it, so the axis keeps its height in decades while the+ /// data grows; otherwise the fixed maximum (1 when it is not positive) with a positive fixed minimum, or the+ /// decades below the maximum when the minimum is not positive or the axis is auto-scaled (data still all+ /// zero, the case of every intensity probe before the wave arrives).+ /// </summary>+ /// <param name="probe">Provides the decades and the fixed range.</param>+ /// <param name="fitted">Whether the axis is auto-scaled and the data has a finite value.</param>+ /// <param name="hi">Largest data value when <paramref name="fitted"/>.</param>+ /// <param name="yMin">Receives the lower limit, positive.</param>+ /// <param name="yMax">Receives the upper limit, greater than <paramref name="yMin"/>.</param>+ private static void LogRange(Probe probe, bool fitted, double hi, ref double yMin, ref double yMax)+ {+ double decades = Math.Clamp(probe.Decades, Probe.MinDecades, Probe.MaxDecades);+ if (fitted && hi > 0.0)+ {+ double top = Math.Log10(hi) + Margin * decades;+ yMax = Math.Pow(10.0, top);+ yMin = Math.Pow(10.0, top - decades);+ return;+ }+ FixedRange(probe, out yMin, out yMax);+ if (!(yMax > 0.0))+ {+ yMax = 1.0;+ }+ if (probe.AutoScaleY || !(yMin > 0.0) || !(yMin < yMax))+ {+ yMin = yMax / Math.Pow(10.0, decades);+ }+ }++ /// <summary>+ /// Tick values of a logarithmic axis over [lo, hi] (both positive): powers of ten, every first, second, third,+ /// fifth or tenth decade so that at most <paramref name="target"/> + 1 of them remain; an axis holding fewer+ /// than two powers of ten gets the "nice" ticks of <see cref="NiceTicks"/> instead (placed by their logarithm).+ /// </summary>+ /// <param name="lo">Lower end of the axis range, positive.</param>+ /// <param name="hi">Upper end of the axis range.</param>+ /// <param name="target">Approximate number of ticks wanted.</param>+ /// <returns>Ascending tick values, all positive.</returns>+ public static List<double> LogTicks(double lo, double hi, int target)+ {+ if (!(lo > 0.0) || !(hi > lo) || double.IsInfinity(hi))+ {+ return [];+ }+ int first = (int)Math.Ceiling(Math.Log10(lo) - 1e-9);+ int last = (int)Math.Floor(Math.Log10(hi) + 1e-9);+ if (last - first < 1)+ {+ return NiceTicks(lo, hi, target).FindAll(t => t > 0.0);+ }+ int every = 10;+ foreach (int candidate in new[] { 1, 2, 3, 5 })+ {+ if ((last - first) / candidate + 1 <= target + 1)+ {+ every = candidate;+ break;+ }+ }+ // the decades counted from a multiple of the spacing, so 1e-6, 1e-4, 1e-2 rather than 1e-5, 1e-3, 1e-1 shifting with the range+ var ticks = new List<double>();+ for (int exponent = first; exponent <= last; exponent++)+ {+ if (exponent % every == 0)+ {+ // a negative power as a division, which is correctly rounded: 1e-6 is the literal 1e-6+ ticks.Add(exponent >= 0 ? Math.Pow(10.0, exponent) : 1.0 / Math.Pow(10.0, -exponent));+ }+ }+ return ticks;+ }++ /// <summary>Formats a logarithmic axis tick: a power of ten from 0.01 to 100 as a plain number, beyond as "1e-6"; other values like <see cref="FormatTick"/>.</summary>+ public static string FormatLogTick(double v, IFormatProvider culture)+ {+ double exponent = Math.Round(Math.Log10(v));+ if (Math.Abs(v / Math.Pow(10.0, exponent) - 1.0) > 1e-6 || Math.Abs(exponent) <= 2)+ {+ return FormatTick(v, culture);+ }+ return "1e" + exponent.ToString("0", culture);+ }++ /// <summary>+ /// The value axis of a laid-out plot: maps a value to a pixel y inside it (bottom edge = minimum, top edge =+ /// maximum), linearly or by the value's logarithm; on a logarithmic axis a value at or below the minimum,+ /// zero and negative values included, lands on the bottom edge. Results are clamped to ±30000 so a renderer+ /// never sees coordinates far outside its surface.+ /// </summary>+ private readonly struct ValueAxis+ {+ private readonly double _lo;+ private readonly double _hi;+ private readonly bool _log;+ private readonly float _plotY;+ private readonly float _plotHeight;++ /// <summary>An axis from <paramref name="min"/> to <paramref name="max"/> (both positive when <paramref name="log"/>) over the plot rows.</summary>+ public ValueAxis(double min, double max, bool log, float plotY, float plotHeight)+ {+ _log = log;+ _lo = log ? Math.Log10(min) : min;+ _hi = log ? Math.Log10(max) : max;+ _plotY = plotY;+ _plotHeight = plotHeight;+ }++ /// <summary>The pixel y of <paramref name="v"/>.</summary>+ public float ToPixel(double v)+ {+ double t = _log ? (v > 0.0 ? Math.Max(Math.Log10(v), _lo) : _lo) : v;+ double py = _plotY + _plotHeight - (t - _lo) / (_hi - _lo) * _plotHeight;+ return (float)Math.Clamp(py, -30000.0, 30000.0);+ }+ }+/// <summary>/// "Nice" (1/2/5 × 10ⁿ) tick positions covering [lo, hi], at most 40 of them. A tick within rounding/// distance of 0 is snapped to exactly 0 so the zero line can be recognised.@@ -476,11 +612,14 @@ public static class ProbeGraph// SeriesRanges, not hidden); only a line probe uses the gated data, to stay blank until it startsComputeRanges(probe, isLine ? shown : data, totalSteps, out double xMin, out double xMax, out double yMin, out double yMax);// the value labels decide the left margin; fewer of them when the plot is low- List<double> yValues = NiceTicks(yMin, yMax, 4);+ bool log = probe.IsLogarithmic;+ List<double> YValues(int target) => log ? LogTicks(yMin, yMax, target) : NiceTicks(yMin, yMax, target);+ string YLabel(double tick) => log ? FormatLogTick(tick, culture) : FormatTick(tick, culture);+ List<double> yValues = YValues(4);float widestY = 0f;foreach (double tick in yValues){- widestY = Math.Max(widestY, style.Measure(FormatTick(tick, culture)));+ widestY = Math.Max(widestY, style.Measure(YLabel(tick)));}float plotX = EdgePad + widestY + LabelGap;float plotY = titleHeight;@@ -509,13 +648,14 @@ public static class ProbeGraph{break;}- yValues = NiceTicks(yMin, yMax, target);+ yValues = YValues(target);}}+ var axis = new ValueAxis(yMin, yMax, log, plotY, plotHeight);var yTicks = new List<GraphTick>();foreach (double tick in yValues){- yTicks.Add(new GraphTick(ToPixelY(tick, plotY, plotHeight, yMin, yMax), showLabels ? FormatTick(tick, culture) : "", tick == 0.0));+ yTicks.Add(new GraphTick(axis.ToPixel(tick), showLabels ? YLabel(tick) : "", tick == 0.0));}// the step/position labels: as many as fit side by side, 5 wantedvar xTicks = new List<GraphTick>();@@ -535,8 +675,8 @@ public static class ProbeGraph}}Vector2[] curve = isLine- ? ProfilePoints(shown.Profile, plotX, plotY, plotWidth, plotHeight, yMin, yMax)- : SeriesPoints(data.Values, data.Count, plotX, plotY, plotWidth, plotHeight, xMin, xMax, yMin, yMax);+ ? ProfilePoints(shown.Profile, plotX, plotWidth, axis)+ : SeriesPoints(data.Values, data.Count, plotX, plotWidth, xMin, xMax, axis);return new ProbeGraphLayout(width, height, true, true, style.FontSize, lineWidth, plotX, plotY, plotWidth, plotHeight, yTicks, xTicks, showLabels, curve, probe.Name, ReadoutText(isLine, shown, culture));}@@ -559,22 +699,12 @@ public static class ProbeGraphreturn float.IsFinite(lastValue) ? "= " + FormatTick(lastValue, culture) : "";}- /// <summary>- /// Maps a data value to a pixel y inside the plot (bottom edge = yMin, top edge = yMax). The result is- /// clamped to ±30000 so a renderer never sees coordinates far outside its surface.- /// </summary>- private static float ToPixelY(double v, float plotY, float plotHeight, double yMin, double yMax)- {- double py = plotY + plotHeight - (v - yMin) / (yMax - yMin) * plotHeight;- return (float)Math.Clamp(py, -30000.0, 30000.0);- }-/// <summary>/// The points of a time series: sample i is placed at x = i + 1 (its step number); NaN and infinite samples/// are skipped. With more than two samples per pixel column each column gets a vertical min/max segment/// instead of individual points./// </summary>- private static Vector2[] SeriesPoints(float[]? values, int count, float plotX, float plotY, float plotWidth, float plotHeight, double xMin, double xMax, double yMin, double yMax)+ private static Vector2[] SeriesPoints(float[]? values, int count, float plotX, float plotWidth, double xMin, double xMax, in ValueAxis axis){if (values == null || count < 1){@@ -598,13 +728,13 @@ public static class ProbeGraphfloat value = values[i];if (float.IsFinite(value)){- points.Add(new Vector2((float)(plotX + (i + 1 - xMin) * xScale), ToPixelY(value, plotY, plotHeight, yMin, yMax)));+ points.Add(new Vector2((float)(plotX + (i + 1 - xMin) * xScale), axis.ToPixel(value)));}}}else{- BinColumns(values, firstIndex, visibleCount, lastIndex, columns, plotX, plotY, plotHeight, yMin, yMax, points);+ BinColumns(values, firstIndex, visibleCount, lastIndex, columns, plotX, axis, points);}return [.. points];}@@ -613,7 +743,7 @@ public static class ProbeGraph/// The points of a line profile stretched over the full plot width (first value at the left edge, last at/// the right edge), min/max binned per pixel column when dense. NaN and infinite values are skipped./// </summary>- private static Vector2[] ProfilePoints(float[]? profile, float plotX, float plotY, float plotWidth, float plotHeight, double yMin, double yMax)+ private static Vector2[] ProfilePoints(float[]? profile, float plotX, float plotWidth, in ValueAxis axis){if (profile == null || profile.Length < 1){@@ -630,13 +760,13 @@ public static class ProbeGraphif (float.IsFinite(value)){double fraction = count > 1 ? i / (count - 1.0) : 0.0;- points.Add(new Vector2((float)(plotX + fraction * plotWidth), ToPixelY(value, plotY, plotHeight, yMin, yMax)));+ points.Add(new Vector2((float)(plotX + fraction * plotWidth), axis.ToPixel(value)));}}}else{- BinColumns(profile, 0, count, count - 1, columns, plotX, plotY, plotHeight, yMin, yMax, points);+ BinColumns(profile, 0, count, count - 1, columns, plotX, axis, points);}return [.. points];}@@ -646,7 +776,7 @@ public static class ProbeGraph/// from first + c × visible / columns on; the long arithmetic keeps c × visible inside the range for/// long runs. Columns without a finite value are skipped./// </summary>- private static void BinColumns(float[] values, int first, int visible, int last, int columns, float plotX, float plotY, float plotHeight, double yMin, double yMax, List<Vector2> points)+ private static void BinColumns(float[] values, int first, int visible, int last, int columns, float plotX, in ValueAxis axis, List<Vector2> points){for (int column = 0; column < columns; column++){@@ -659,8 +789,8 @@ public static class ProbeGraphif (Extent(values, binStart, Math.Min(binEnd, last), out float binMin, out float binMax)){float px = plotX + column + 0.5f;- points.Add(new Vector2(px, ToPixelY(binMin, plotY, plotHeight, yMin, yMax)));- points.Add(new Vector2(px, ToPixelY(binMax, plotY, plotHeight, yMin, yMax)));+ points.Add(new Vector2(px, axis.ToPixel(binMin)));+ points.Add(new Vector2(px, axis.ToPixel(binMax)));}}}diff --git a/_tools/library_check/Program.cs b/_tools/library_check/Program.csindex 74ed7c6..e475087 100644--- a/_tools/library_check/Program.cs+++ b/_tools/library_check/Program.cs@@ -1696,6 +1696,36 @@ internal static class ProgramProbeGraphLayout after = ProbeGraph.Layout(line, new ProbeGraphData(null, 0, profile, 49, 100), 2500, 400, 200, style, inv);Check(before.Curve.Length == 0 && before.Readout == "" && before.XTicks[^1].Label == "1", "line probe blank before its start step");Check(after.Curve.Length == 50 && after.Readout == "max 4.9" && after.XTicks[^1].Label == "40" && after.YTicks[0].Label == "0", "line probe after its start step: profile over 0..49 pixels, intensity fitted from 0");++ // a logarithmic value axis: intensity only, the decades below a fitted top, zeros on the bottom line+ var logProbe = new Probe { Name = "Log", Layer = ProbeLayer.Intensity, YScale = ProbeValueScale.Logarithmic };+ float[] spread = new float[16];+ spread[2] = 1e-5f;+ spread[9] = 0.01f;+ ProbeGraph.ComputeRanges(logProbe, new ProbeGraphData(spread, 16, null, 0, 16), 2500, out _, out _, out double logMin, out double logMax);+ Check(logProbe.IsLogarithmic && Math.Abs(Math.Log10(logMax) - (-2 + 0.48)) < 1e-6 && Math.Abs(Math.Log10(logMax / logMin) - 6) < 1e-9,+ "log axis: six decades below the largest value raised by 8 % of the axis (" + logMin.ToString("G3", inv) + ".." + logMax.ToString("G3", inv) + ")");+ ProbeGraph.ComputeRanges(logProbe, new ProbeGraphData(new float[16], 16, null, 0, 16), 2500, out _, out _, out double logZeroMin, out double logZeroMax);+ Check(logZeroMax == 1 && Math.Abs(logZeroMin - 1e-6) < 1e-18, "log axis on all-zero data: the fixed top (1 for -1..1), six decades below it");+ logProbe.AutoScaleY = false;+ logProbe.YMin = 1e-4;+ logProbe.YMax = 10;+ ProbeGraph.ComputeRanges(logProbe, default, 2500, out _, out _, out double logFixedMin, out double logFixedMax);+ Check(logFixedMin == 1e-4 && logFixedMax == 10, "log axis, fixed: a positive minimum is the bottom");+ logProbe.AutoScaleY = true;+ ProbeGraphLayout logLayout = ProbeGraph.Layout(logProbe, new ProbeGraphData(spread, 16, null, 0, 16), 2500, 400, 200, style, inv);+ float bottom = logLayout.PlotY + logLayout.PlotHeight;+ Check(logLayout.YTicks.All(t => !t.IsZero) && string.Join(" ", logLayout.YTicks.Select(t => t.Label)) == "1e-6 1e-4 0.01",+ "log axis ticks: every second power of ten over 1e-7.5..1e-1.5 (" + string.Join(" ", logLayout.YTicks.Select(t => t.Label)) + ")");+ Check(logLayout.Curve.Length == 16 && logLayout.Curve.Count(p => Math.Abs(p.Y - bottom) < 0.01) == 14 && logLayout.Curve[9].Y < logLayout.Curve[2].Y && logLayout.Curve[9].Y > logLayout.PlotY,+ "log axis: zeros on the bottom line, 0.01 above 1e-5, both inside the plot");+ Check(ProbeGraph.LogTicks(1e-6, 1, 4) is [1e-6, 1e-4, 1e-2, 1] && ProbeGraph.LogTicks(1e-12, 1, 4) is [1e-12, 1e-9, 1e-6, 1e-3, 1] && ProbeGraph.LogTicks(2, 8, 4).All(t => t is > 0 and <= 8),+ "log ticks: every second or third decade, aligned; nice ticks within a decade");+ Check(ProbeGraph.FormatLogTick(1e-6, inv) == "1e-6" && ProbeGraph.FormatLogTick(0.01, inv) == "0.01" && ProbeGraph.FormatLogTick(1e3, inv) == "1e3" && ProbeGraph.FormatLogTick(5, inv) == "5", "log tick labels: plain from 0.01 to 100, 1e-n beyond");+ logProbe.Layer = ProbeLayer.Field;+ var normalised = new Probe { Layer = ProbeLayer.Intensity, YScale = ProbeValueScale.Logarithmic, Decades = 40 };+ normalised.Normalize();+ Check(logProbe is { YScale: ProbeValueScale.Linear, IsLogarithmic: false } && normalised.Decades == 12 && normalised.IsLogarithmic, "a field probe's axis is linear; the decades are clamped to 12");}/// <summary>The repository root (the folder holding the author's examples), found by walking up from the harness binary; null when not found.</summary>