### Run FFTSharp Benchmarks Source: https://github.com/swharden/fftsharp/blob/main/src/FftSharp.Benchmark/Benchmarking.md Execute this command within the src/FftSharp.Benchmark directory to start the performance test suite. ```bash dotnet run -c Release ``` -------------------------------- ### Mel Frequency Scaling Example Source: https://context7.com/swharden/fftsharp/llms.txt Demonstrates converting between linear frequency (Hz) and Mel scale, and computing a Mel-scaled spectrum from audio magnitude data. Requires FftSharp and System.Numerics namespaces. ```csharp using FftSharp; using System.Numerics; double[] signal = SampleData.SampleAudio1(); int sampleRate = 48000; // Compute FFT magnitude Complex[] spectrum = FFT.Forward(signal); double[] magnitude = FFT.Magnitude(spectrum); // Convert to Mel scale with specified number of bins int melBins = 40; double[] melSpectrum = Mel.Scale(magnitude, sampleRate, melBins); // Convert individual frequencies double freq = 1000; // Hz double mel = Mel.FromFreq(freq); double backToHz = Mel.ToFreq(mel); Console.WriteLine($"1000 Hz = {mel:F1} Mel"); Console.WriteLine($"{mel:F1} Mel = {backToHz:F1} Hz"); Console.WriteLine($"Mel spectrum bins: {melSpectrum.Length}"); ``` -------------------------------- ### Sample Data Generation Source: https://context7.com/swharden/fftsharp/llms.txt Shows how to generate various test signals using the SampleData class, including pre-made audio, time values, sine waves, custom signals with added tones and noise, and random normal distributions. Requires FftSharp namespace. ```csharp using FftSharp; // Pre-made audio sample (48 kHz with tones at 2, 10, 20 kHz + noise) double[] audio = SampleData.SampleAudio1(); Console.WriteLine($"Sample audio length: {audio.Length}"); // Generate time values for plotting double[] times = SampleData.Times(sampleRate: 48000, pointCount: 512); // Generate odd harmonics (square wave approximation) double[] oddSines = SampleData.OddSines(pointCount: 256, sineCount: 5); // Create custom signal with specific tones double[] custom = new double[512]; SampleData.AddSin(custom, sampleRate: 48000, frequency: 1000, magnitude: 1.0); SampleData.AddSin(custom, sampleRate: 48000, frequency: 5000, magnitude: 0.5); SampleData.AddOffset(custom, offset: 0.1); // Add DC offset SampleData.AddWhiteNoise(custom, magnitude: 0.05, seed: 42); // Generate random normal distribution double[] noise = SampleData.RandomNormal(pointCount: 256, mean: 0, stdDev: 1, seed: 123); ``` -------------------------------- ### Readme File Source: https://github.com/swharden/fftsharp/blob/main/dev/imp/ooura/readme.md This file contains the readme information for the FFT package. ```text readme.txt : Readme File ``` -------------------------------- ### Perform FFT analysis with FftSharp Source: https://github.com/swharden/fftsharp/blob/main/src/FftSharp/README.md Demonstrates the workflow of applying a window function to a signal and calculating its frequency spectrum. ```csharp // Begin with an array containing sample data double[] signal = FftSharp.SampleData.SampleAudio1(); // Shape the signal using a Hanning window var window = new FftSharp.Windows.Hanning(); window.ApplyInPlace(signal); // Calculate the FFT as an array of complex numbers System.Numerics.Complex[] spectrum = FftSharp.FFT.Forward(signal); // or get the magnitude (units²) or power (dB) as real numbers double[] magnitude = FftSharp.FFT.Magnitude(spectrum); double[] power = FftSharp.FFT.Power(spectrum); ``` -------------------------------- ### BluesteinSizeBenchmark Environment Info Source: https://github.com/swharden/fftsharp/blob/main/src/FftSharp.Benchmark/Benchmarking.md System and runtime configuration details for the BluesteinSizeBenchmark execution. ```text BenchmarkDotNet v0.13.11, Windows 11 (10.0.22631.2861/23H2/2023Update/SunValley3) Intel Core i7-1065G7 CPU 1.30GHz, 1 CPU, 8 logical and 4 physical cores .NET SDK 8.0.100 [Host] : .NET 6.0.25 (6.0.2523.51912), X64 RyuJIT AVX2 .NET 6.0 : .NET 6.0.25 (6.0.2523.51912), X64 RyuJIT AVX2 .NET 8.0 : .NET 8.0.0 (8.0.23.53103), X64 RyuJIT AVX-512F+CD+BW+DQ+VL+VBMI ``` -------------------------------- ### Test Program Fortran Makefile Source: https://github.com/swharden/fftsharp/blob/main/dev/imp/ooura/readme.md Makefile for the test programs using the FFT package with Fortran. ```makefile Makefile.f77: for Fortran ``` -------------------------------- ### Test Program Simple C Source: https://github.com/swharden/fftsharp/blob/main/dev/imp/ooura/readme.md Test program in C for the 'fft*g_h.c' routines. ```c testxg_h.c : Test Program for "fft*g_h.c" ``` -------------------------------- ### Test Program Makefile Source: https://github.com/swharden/fftsharp/blob/main/dev/imp/ooura/readme.md Makefile for the test programs using the FFT package with gcc or cc. ```makefile Makefile : for gcc, cc ``` -------------------------------- ### Test Program Fortran Source: https://github.com/swharden/fftsharp/blob/main/dev/imp/ooura/readme.md Test program in Fortran for the 'fft*g.f' routines. ```fortran testxg.f : Test Program for "fft*g.f" ``` -------------------------------- ### PI Calculation Benchmark Program Source: https://github.com/swharden/fftsharp/blob/main/dev/imp/ooura/readme.md A C program for benchmarking the FFT package by calculating PI. ```c pi_fft.c : PI(= 3.1415926535897932384626...) Calculation Program for a Benchmark Test for "fft*g.c" ``` -------------------------------- ### Test Program C Source: https://github.com/swharden/fftsharp/blob/main/dev/imp/ooura/readme.md Test program in C for the 'fft*g.c' routines. ```c testxg.c : Test Program for "fft*g.c" ``` -------------------------------- ### C FFT Package (Simple Version I) Source: https://github.com/swharden/fftsharp/blob/main/dev/imp/ooura/readme.md This file contains the Simple Version I of the FFT package in C, utilizing a radix 4,2 algorithm. It does not use a work area. ```c fft4g_h.c : FFT Package in C - Simple Version I (radix 4,2) ``` -------------------------------- ### Fortran FFT Package (Fast Version I) Source: https://github.com/swharden/fftsharp/blob/main/dev/imp/ooura/readme.md This file contains the Fast Version I of the FFT package in Fortran, utilizing a radix 4,2 algorithm. It is equivalent to the C version. ```fortran fft4g.f : FFT Package in Fortran - Fast Version I (radix 4,2) ``` -------------------------------- ### C FFT Package (Simple Split-Radix) Source: https://github.com/swharden/fftsharp/blob/main/dev/imp/ooura/readme.md This file contains the Simple Split-Radix version of the FFT package in C. It does not use a work area and is optimized for machines with multi-level caches. ```c fftsg_h.c : FFT Package in C - Simple Version III (Split-Radix) ``` -------------------------------- ### C FFT Package (Simple Version II) Source: https://github.com/swharden/fftsharp/blob/main/dev/imp/ooura/readme.md This file contains the Simple Version II of the FFT package in C, utilizing a radix 8,4,2 algorithm. It does not use a work area. ```c fft8g_h.c : FFT Package in C - Simple Version II (radix 8,4,2) ``` -------------------------------- ### C FFT Package (Fast Version II) Source: https://github.com/swharden/fftsharp/blob/main/dev/imp/ooura/readme.md This file contains the Fast Version II of the FFT package in C, utilizing a radix 8,4,2 algorithm. It is fast on UltraSPARC machines. ```c fft8g.c : FFT Package in C - Fast Version II (radix 8,4,2) ``` -------------------------------- ### C FFT Package (Fast Version I) Source: https://github.com/swharden/fftsharp/blob/main/dev/imp/ooura/readme.md This file contains the Fast Version I of the FFT package in C, utilizing a radix 4,2 algorithm. It is optimized for most machines. ```c fft4g.c : FFT Package in C - Fast Version I (radix 4,2) ``` -------------------------------- ### Fortran FFT Package (Split-Radix) Source: https://github.com/swharden/fftsharp/blob/main/dev/imp/ooura/readme.md This file contains the Split-Radix version of the FFT package in Fortran. It is equivalent to the C version. ```fortran fftsg.f : FFT Package in Fortran - Fast Version III (Split-Radix) ``` -------------------------------- ### Fortran FFT Package (Fast Version II) Source: https://github.com/swharden/fftsharp/blob/main/dev/imp/ooura/readme.md This file contains the Fast Version II of the FFT package in Fortran, utilizing a radix 8,4,2 algorithm. It is equivalent to the C version. ```fortran fft8g.f : FFT Package in Fortran - Fast Version II (radix 8,4,2) ``` -------------------------------- ### cdft Method (In-place, Radix 2^M) Source: https://github.com/swharden/fftsharp/blob/main/dev/imp/ooura/readme.md Describes the in-place, radix 2^M, Sande-Tukey method for cdft (Complex Discrete Fourier Transform) using bit-reverse order for continuous memory access. ```text fft4g*.*, fft8g*.*: A method of in-place, radix 2^M, Sande-Tukey (decimation in frequency). Index of the butterfly loop is in bit reverse order to keep continuous memory access. fftsg*.*: A method of in-place, Split-Radix, recursive fast algorithm. ``` -------------------------------- ### Compute Discrete Fourier Transform (DFT) Source: https://context7.com/swharden/fftsharp/llms.txt Provides a straightforward, though slower, implementation of the discrete Fourier Transform. Useful for educational purposes or when standard FFT is not applicable. ```csharp using FftSharp; using System.Numerics; // Forward DFT (works with any array length) double[] signal = { 1, 2, 3, 4, 5 }; Complex[] spectrum = DFT.Forward(signal); // With Complex input Complex[] complexSignal = signal.Select(x => new Complex(x, 0)).ToArray(); Complex[] spectrumFromComplex = DFT.Forward(complexSignal); // Inverse DFT Complex[] recovered = DFT.Inverse(spectrum); Console.WriteLine("DFT Results:"); for (int i = 0; i < spectrum.Length; i++) { Console.WriteLine($"Bin {i}: {spectrum[i].Magnitude:F3}"); } ``` -------------------------------- ### C FFT Package (Split-Radix) Source: https://github.com/swharden/fftsharp/blob/main/dev/imp/ooura/readme.md This file contains the Split-Radix version of the FFT package in C. It is optimized for machines with multi-level caches. ```c fftsg.c : FFT Package in C - Fast Version III (Split-Radix) ``` -------------------------------- ### Plot Sample Audio Data Source: https://github.com/swharden/fftsharp/blob/main/README.md Uses ScottPlot to visualize sample audio data in the time domain. ```cs // sample audio with tones at 2, 10, and 20 kHz plus white noise double[] signal = FftSharp.SampleData.SampleAudio1(); int sampleRate = 48_000; double samplePeriod = sampleRate / 1000.0; // plot the sample audio ScottPlot.Plot plt = new(); plt.Add.Signal(signal, samplePeriod); plt.YLabel("Amplitude"); plt.SavePng("time-series.png", 500, 200); ``` -------------------------------- ### Benchmark POSIX Thread Makefile Source: https://github.com/swharden/fftsharp/blob/main/dev/imp/ooura/readme.md Makefile for the benchmark programs using the FFT package with POSIX Threads. ```makefile Makefile.pth: POSIX Thread version ``` -------------------------------- ### dfct Method Explanation Source: https://github.com/swharden/fftsharp/blob/main/dev/imp/ooura/readme.md Explains the method for dfct (Cosine Transform of RDFT) which splits into 'dfct' and 'ddct' of half length. It details the decomposition of the transform and the recursive use of 'ddct'. ```text The transform : C[k] = sum_j=0^n a[j]*cos(pi*j*k/n), 0<=k<=n is divided into : C[2*k] = sum'_j=0^n/2 (a[j]+a[n-j])*cos(pi*j*k/(n/2)), C[2*k+1] = sum_j=0^n/2-1 (a[j]-a[n-j])*cos(pi*j*(k+1/2)/(n/2)) (sum' is a summation whose last term multiplies 1/2). This routine uses "ddct" recursively. To keep the in-place operation, the data in fft*g_h.* are sorted in bit reversal order. ``` -------------------------------- ### Compute Inverse FFT with FftSharp Source: https://context7.com/swharden/fftsharp/llms.txt Converts frequency-domain data back to the time domain using in-place transformation. ```csharp using FftSharp; using System.Numerics; // Transform signal to frequency domain double[] signal = SampleData.SampleAudio1(); Complex[] spectrum = FFT.Forward(signal); // Modify spectrum (e.g., filtering) // ... apply modifications ... // Convert back to time domain FFT.Inverse(spectrum); // Extract real values from the result double[] reconstructed = new double[spectrum.Length]; for (int i = 0; i < spectrum.Length; i++) reconstructed[i] = spectrum[i].Real; ``` -------------------------------- ### rdft Method Explanation Source: https://github.com/swharden/fftsharp/blob/main/dev/imp/ooura/readme.md Explains the method for rdft (Real Discrete Fourier Transform) which appends a butterfly operation to cdft. It details the transformation of the input array and the calculation of the output array A[k]. ```text In forward transform : A[k] = sum_j=0^n-1 a[j]*W(n)^(j*k), 0<=k<=n/2, W(n) = exp(2*pi*i/n), this routine makes an array x[] : x[j] = a[2*j] + i*a[2*j+1], 0<=j) - Required - High-performance buffer for in-place transformation. ### Request Example // Forward FFT from real-valued samples Complex[] spectrum = FFT.Forward(signal); // Forward FFT in-place on Complex array FFT.Forward(buffer); ``` -------------------------------- ### Apply Hanning Window Source: https://github.com/swharden/fftsharp/blob/main/README.md Applies a Hanning window to a signal array to improve frequency resolution. ```cs double[] signal = FftSharp.SampleData.SampleAudio1(); var window = new FftSharp.Windows.Hanning(); double[] windowed = window.Apply(signal); ``` -------------------------------- ### Compute FFT for Arbitrary-Length Arrays with Bluestein Source: https://context7.com/swharden/fftsharp/llms.txt Enables FFT computation on arrays of any length, not just powers of 2, using Bluestein's chirp z-transform algorithm. ```csharp using FftSharp; using System.Numerics; // Create signal with non-power-of-2 length double[] signal = new double[500]; // 500 is not a power of 2 for (int i = 0; i < signal.Length; i++) signal[i] = Math.Sin(2 * Math.PI * 10 * i / 100); // Compute FFT using Bluestein algorithm (works with any length) Complex[] spectrum = Bluestein.Forward(signal); // In-place forward transform on Complex array Complex[] buffer = signal.Select(x => new Complex(x, 0)).ToArray(); Bluestein.Forward(buffer); // Inverse transform Complex[] recovered = Bluestein.Inverse(signal); Console.WriteLine($"Input length: {signal.Length} (not power of 2)"); Console.WriteLine($"Spectrum length: {spectrum.Length}"); ``` -------------------------------- ### Calculate Power Spectral Density in dB Source: https://context7.com/swharden/fftsharp/llms.txt Computes the power spectral density in decibels (dB) from an FFT spectrum. Useful for audio analysis where logarithmic scaling is preferred. Requires FFT.Forward to be computed first. ```csharp using FftSharp; using System.Numerics; double[] signal = SampleData.SampleAudio1(); int sampleRate = 48000; // Compute FFT and power spectral density Complex[] spectrum = FFT.Forward(signal); double[] powerDb = FFT.Power(spectrum); double[] frequencies = FFT.FrequencyScale(powerDb.Length, sampleRate); // Display power at specific frequencies for (int i = 0; i < powerDb.Length; i += powerDb.Length / 10) { Console.WriteLine($"{frequencies[i]:F1} Hz: {powerDb[i]:F2} dB"); } ``` -------------------------------- ### Generate Frequency Axis for FFT Bins Source: https://context7.com/swharden/fftsharp/llms.txt Generates an array of frequency values (in Hz) corresponding to FFT bins. Can generate frequencies for positive-only or full spectrum, and calculate frequency resolution. Use FFT.Forward to obtain the spectrum first. ```csharp using FftSharp; using System.Numerics; double[] signal = SampleData.SampleAudio1(); int sampleRate = 48000; Complex[] spectrum = FFT.Forward(signal); double[] power = FFT.Power(spectrum); // Get frequencies for positive-only spectrum (default) double[] freqPositive = FFT.FrequencyScale(power.Length, sampleRate); // Get frequencies including negative frequencies double[] freqFull = FFT.FrequencyScale(spectrum.Length, sampleRate, positiveOnly: false); // Get frequency resolution (Hz per bin) double resolution = FFT.FrequencyResolution(power.Length, sampleRate); Console.WriteLine($"Frequency resolution: {resolution:F2} Hz"); Console.WriteLine($"Max frequency (Nyquist): {freqPositive[^1]:F0} Hz"); ``` -------------------------------- ### Compute Forward FFT with FftSharp Source: https://context7.com/swharden/fftsharp/llms.txt Computes the discrete Fourier Transform using real or complex arrays. Input length must be a power of 2. ```csharp using FftSharp; using System.Numerics; // Forward FFT from real-valued samples (returns new Complex array) double[] signal = SampleData.SampleAudio1(); Complex[] spectrum = FFT.Forward(signal); // Forward FFT in-place on Complex array Complex[] buffer = new Complex[] { new(42, 0), new(96, 0), new(13, 0), new(99, 0), new(58, 0), new(17, 0), new(24, 0), new(89, 0) }; FFT.Forward(buffer); // Transforms buffer in-place // Using Span for high-performance scenarios Span spanBuffer = stackalloc Complex[8]; // ... fill spanBuffer ... FFT.Forward(spanBuffer); ``` -------------------------------- ### ddct Method Explanation Source: https://github.com/swharden/fftsharp/blob/main/dev/imp/ooura/readme.md Explains the method for ddct (Discrete Cosine Transform) which appends a butterfly operation to rdft. It details the transformation of the input array and the calculation of the output array C[k]. ```text In backward transform : C[k] = sum_j=0^n-1 a[j]*cos(pi*j*(k+1/2)/n), 0<=k 128 // Pad Complex array to next power of 2 Complex[] complexSignal = new Complex[300]; Complex[] paddedComplex = Pad.ZeroPad(complexSignal); Console.WriteLine($"Padded from {complexSignal.Length} to {paddedComplex.Length}"); // 300 -> 512 // Pad to specific length double[] paddedToSize = Pad.ZeroPad(signal, finalLength: 1024); Console.WriteLine($"Padded to specific length: {paddedToSize.Length}"); // 1024 ``` -------------------------------- ### Apply Window Functions to Signals Source: https://context7.com/swharden/fftsharp/llms.txt Shapes signal data before FFT to reduce spectral leakage. Supports various window types like Hanning, Hamming, and Kaiser. ```csharp using FftSharp; using FftSharp.Windows; double[] signal = SampleData.SampleAudio1(); // Create and apply a Hanning window (most common choice) var hanning = new Hanning(); double[] windowedSignal = hanning.Apply(signal); // Apply window in-place to modify original array var hamming = new Hamming(); double[] signal2 = (double[])signal.Clone(); hamming.ApplyInPlace(signal2); // Create a Kaiser window with custom beta parameter var kaiser = new Kaiser(beta: 14); double[] kaiserWindowed = kaiser.Apply(signal); // Get just the window shape (for visualization) double[] windowShape = hanning.Create(512); double[] normalizedWindow = hanning.Create(512, normalize: true); // List all available window functions IWindow[] allWindows = Window.GetWindows(); foreach (var w in allWindows) { Console.WriteLine($"{w.Name}: {w.Description.Substring(0, 50)}..."); } ``` -------------------------------- ### Convert Amplitude to Logarithmic Units Source: https://github.com/swharden/fftsharp/blob/main/dev/notes/readme.md Formulas for calculating power in decibels from amplitude values. ```text Power (dB) = 2 * 10 * Log10(amplitude / reference) ``` ```text magnitude = FFTpos * 2 / N dB = 2 * 10 * np.log10(magnitude / reference) ``` -------------------------------- ### Compute Inverse Real FFT Source: https://context7.com/swharden/fftsharp/llms.txt Reconstructs a time-domain signal from a positive-frequency spectrum, returning only real values. ```csharp using FftSharp; using System.Numerics; // Get the real spectrum (positive frequencies only) double[] signal = SampleData.SampleAudio1(); Complex[] realSpectrum = FFT.ForwardReal(signal); // Modify the spectrum if needed // ... apply modifications ... // Reconstruct the time-domain signal (returns only real values) double[] reconstructed = FFT.InverseReal(realSpectrum); // reconstructed now contains the time-domain signal as double[] Console.WriteLine($"Reconstructed {reconstructed.Length} samples"); ``` -------------------------------- ### Convert FFT to Single-Sided Amplitude Spectrum Source: https://github.com/swharden/fftsharp/blob/main/dev/notes/readme.md Iterative approach to convert a two-sided FFT output into a single-sided amplitude spectrum in RMS units. ```cs int N = FFT.Length; // convert FFT to amplitude spectrum (single-sided) for (int i=1; i< N/2; i++) Amplitude[i] = sqrt(2) * FFT[i].Magnitude / N // special case for first (DC) bin Amplitude[0] = Magnitude(FFT[i]) / N ``` -------------------------------- ### Center Zero-Frequency Component in FFT Output Source: https://context7.com/swharden/fftsharp/llms.txt Rearranges FFT output so the zero-frequency (DC) component is at the center of the array. Useful for visualization and signal processing. Requires FFT.Forward and FFT.Magnitude to be computed first. ```csharp using FftSharp; using System.Numerics; double[] signal = SampleData.SampleAudio1(); Complex[] spectrum = FFT.Forward(signal); // Get magnitude with negative frequencies included double[] magnitude = FFT.Magnitude(spectrum, positiveOnly: false); // Shift so DC is at center (standard FFT visualization format) double[] shiftedMagnitude = FFT.FftShift(magnitude); // Now index 0 = most negative freq, center = DC, end = most positive freq Console.WriteLine($"DC component now at index: {shiftedMagnitude.Length / 2}"); ``` -------------------------------- ### Apply Band-Stop Filter to Signal Source: https://context7.com/swharden/fftsharp/llms.txt Removes frequencies within a specified range. Useful for eliminating specific interference like power line noise. ```csharp using FftSharp; double[] signal = SampleData.SampleAudio1(); int sampleRate = 48000; // Remove frequencies between 50 Hz and 60 Hz (power line interference) double[] filtered = Filter.BandStop(signal, sampleRate, minFrequency: 50, maxFrequency: 60); Console.WriteLine($"Notch filter applied: removed 50-60 Hz"); ``` -------------------------------- ### FFT.InverseReal Source: https://context7.com/swharden/fftsharp/llms.txt Computes the inverse FFT and returns only the real component from a positive-frequency spectrum. ```APIDOC ## FFT.InverseReal ### Description Reconstructs the full time-domain signal from a positive-frequency spectrum (length = windowSize/2 + 1). ### Method Static Method ### Parameters #### Request Body - **realSpectrum** (Complex[]) - Required - Positive-frequency spectrum. ### Response #### Success Response (200) - **reconstructed** (double[]) - The time-domain signal. ``` -------------------------------- ### Calculate and Plot Power Spectral Density Source: https://github.com/swharden/fftsharp/blob/main/README.md Calculates the power spectral density of a signal and plots it against frequency using ScottPlot. ```cs // sample audio with tones at 2, 10, and 20 kHz plus white noise double[] signal = FftSharp.SampleData.SampleAudio1(); int sampleRate = 48_000; // calculate the power spectral density using FFT System.Numerics.Complex[] spectrum = FftSharp.FFT.Forward(signal); double[] psd = FftSharp.FFT.Power(spectrum); double[] freq = FftSharp.FFT.FrequencyScale(psd.Length, sampleRate); // plot the sample audio ScottPlot.Plot plt = new(); plt.Add.ScatterLine(freq, psd); plt.YLabel("Power (dB)"); plt.XLabel("Frequency (Hz)"); plt.SavePng("periodogram.png", 500, 200); ``` -------------------------------- ### FFT.Magnitude Source: https://context7.com/swharden/fftsharp/llms.txt Calculates the power spectral density in RMS units from a Complex spectrum. ```APIDOC ## FFT.Magnitude ### Description Calculates the magnitude spectrum, handling proper scaling for positive and negative frequencies. ### Method Static Method ### Parameters #### Request Body - **spectrum** (Complex[]) - Required - The complex spectrum to analyze. - **positiveOnly** (bool) - Optional - Whether to return only positive frequencies (default: true). ### Response #### Success Response (200) - **magnitude** (double[]) - The calculated magnitude spectrum. ``` -------------------------------- ### FFT.Power - Calculate Power Spectral Density in dB Source: https://context7.com/swharden/fftsharp/llms.txt Computes the power spectral density in decibels (dB) from a Complex spectrum array. Useful for audio analysis and visualization with logarithmic scaling. ```APIDOC ## FFT.Power - Calculate Power Spectral Density in dB ### Description Computes the power spectral density in decibels (dB) from a Complex spectrum array. This is commonly used for audio analysis and visualization where logarithmic scaling better represents human perception. ### Method `FFT.Power` ### Parameters #### Request Body - **spectrum** (Complex[]) - Required - The complex spectrum array obtained from an FFT. - **positiveOnly** (bool) - Optional - If true (default), only positive frequencies are considered. If false, both positive and negative frequencies are included. ### Response #### Success Response (200) - **powerDb** (double[]) - An array of power spectral density values in decibels. ### Request Example ```csharp using FftSharp; using System.Numerics; double[] signal = SampleData.SampleAudio1(); int sampleRate = 48000; // Compute FFT and power spectral density Complex[] spectrum = FFT.Forward(signal); double[] powerDb = FFT.Power(spectrum); ``` ### Response Example ```csharp // Example output for powerDb array // [ -120.5, -110.2, -95.8, ... ] ``` ``` -------------------------------- ### Calculate Magnitude Spectrum Source: https://context7.com/swharden/fftsharp/llms.txt Computes power spectral density in RMS units from a complex spectrum, with options for positive-only or full frequency ranges. ```csharp using FftSharp; using System.Numerics; double[] signal = SampleData.SampleAudio1(); int sampleRate = 48000; // Compute FFT Complex[] spectrum = FFT.Forward(signal); // Get magnitude (positive frequencies only - default) double[] magnitude = FFT.Magnitude(spectrum); // Get magnitude including negative frequencies double[] magnitudeFull = FFT.Magnitude(spectrum, positiveOnly: false); // Get corresponding frequency values double[] frequencies = FFT.FrequencyScale(magnitude.Length, sampleRate); // Find peak frequency int peakIndex = Array.IndexOf(magnitude, magnitude.Max()); double peakFrequency = frequencies[peakIndex]; Console.WriteLine($"Peak frequency: {peakFrequency} Hz"); ``` -------------------------------- ### Apply Band-Pass Frequency Filter Source: https://context7.com/swharden/fftsharp/llms.txt Retains only frequencies within a specified range, silencing everything outside the band. The filtered signal has the same length as the original. ```csharp using FftSharp; double[] signal = SampleData.SampleAudio1(); int sampleRate = 48000; // Keep only frequencies between 1000 Hz and 5000 Hz double[] filtered = Filter.BandPass(signal, sampleRate, minFrequency: 1000, maxFrequency: 5000); Console.WriteLine($"Band-pass filtered: 1000-5000 Hz"); ``` -------------------------------- ### Apply Low-Pass Filter Source: https://github.com/swharden/fftsharp/blob/main/README.md Filters a signal using a low-pass filter with a specified cutoff frequency. ```cs double[] audio = FftSharp.SampleData.SampleAudio1(); double[] filtered = FftSharp.Filter.LowPass(audio, sampleRate: 48000, maxFrequency: 2000); ``` -------------------------------- ### Calculate FFT Resolution Source: https://github.com/swharden/fftsharp/blob/main/dev/notes/readme.md Formula to determine the frequency resolution of an FFT based on sample length and period. ```cs var Resolution = 1.0 / (sampleLength * samplePeriod) ``` -------------------------------- ### FFT.Inverse Source: https://context7.com/swharden/fftsharp/llms.txt Applies the inverse Fast Fourier Transform to convert frequency-domain data back to the time domain. ```APIDOC ## FFT.Inverse ### Description Converts frequency-domain data back to the time domain. The input Complex array is transformed in-place and its length must be a power of 2. ### Method Static Method ### Parameters #### Request Body - **spectrum** (Complex[]) - Required - Frequency-domain data to transform. ### Request Example // Convert back to time domain FFT.Inverse(spectrum); ``` -------------------------------- ### FFT.FrequencyScale - Generate Frequency Axis Source: https://context7.com/swharden/fftsharp/llms.txt Generates an array of frequency values (in Hz) corresponding to each FFT bin. Essential for plotting spectra against frequency. ```APIDOC ## FFT.FrequencyScale - Generate Frequency Axis ### Description Generates an array of frequency values (in Hz) corresponding to each FFT bin. This is essential for plotting spectra against frequency rather than bin index. ### Method `FFT.FrequencyScale` ### Parameters #### Path Parameters - **binCount** (int) - Required - The number of bins in the FFT spectrum (e.g., `power.Length` or `spectrum.Length`). - **sampleRate** (int) - Required - The sample rate of the original signal in Hz. #### Query Parameters - **positiveOnly** (bool) - Optional - If true (default), frequencies range from 0 Hz up to the Nyquist frequency. If false, frequencies range from negative Nyquist up to positive Nyquist. ### Response #### Success Response (200) - **frequencies** (double[]) - An array of frequency values in Hz. ### Request Example ```csharp using FftSharp; using System.Numerics; double[] signal = SampleData.SampleAudio1(); int sampleRate = 48000; Complex[] spectrum = FFT.Forward(signal); double[] power = FFT.Power(spectrum); // Get frequencies for positive-only spectrum (default) double[] freqPositive = FFT.FrequencyScale(power.Length, sampleRate); // Get frequencies including negative frequencies double[] freqFull = FFT.FrequencyScale(spectrum.Length, sampleRate, positiveOnly: false); ``` ### Response Example ```csharp // Example output for freqPositive array (assuming power.Length = 1024, sampleRate = 48000) // [ 0.0, 46.875, 93.75, ..., 23953.125 ] // Example output for freqFull array (assuming spectrum.Length = 1024, sampleRate = 48000) // [ -24000.0, -23953.125, ..., 0.0, ..., 23953.125 ] ``` ``` -------------------------------- ### Extract Phase Information from Complex Spectrum Source: https://context7.com/swharden/fftsharp/llms.txt Extracts the phase angle in radians from each point in a Complex spectrum array. Requires FFT.Forward to be computed first. Phase can be converted to degrees if needed. ```csharp using FftSharp; using System.Numerics; double[] signal = SampleData.SampleAudio1(); Complex[] spectrum = FFT.Forward(signal); // Get phase for each frequency bin (in radians) double[] phase = FFT.Phase(spectrum); // Convert to degrees if needed double[] phaseDegrees = phase.Select(p => p * 180 / Math.PI).ToArray(); Console.WriteLine($"Phase values range: {phase.Min():F3} to {phase.Max():F3} radians"); ``` -------------------------------- ### Perform In-Place FFT on Complex Array Source: https://github.com/swharden/fftsharp/blob/main/README.md Executes an FFT operation directly on an array of complex numbers. ```cs System.Numerics.Complex[] buffer = { new(real: 42, imaginary: 12), new(real: 96, imaginary: 34), new(real: 13, imaginary: 56), new(real: 99, imaginary: 78), }; FftSharp.FFT.Forward(buffer); ``` -------------------------------- ### FFT.Phase - Extract Phase Information Source: https://context7.com/swharden/fftsharp/llms.txt Extracts the phase angle (in radians) from each point in a Complex spectrum array. ```APIDOC ## FFT.Phase - Extract Phase Information ### Description Extracts the phase angle (in radians) from each point in a Complex spectrum array. ### Method `FFT.Phase` ### Parameters #### Request Body - **spectrum** (Complex[]) - Required - The complex spectrum array obtained from an FFT. ### Response #### Success Response (200) - **phase** (double[]) - An array of phase angles in radians. ### Request Example ```csharp using FftSharp; using System.Numerics; double[] signal = SampleData.SampleAudio1(); Complex[] spectrum = FFT.Forward(signal); // Get phase for each frequency bin (in radians) double[] phase = FFT.Phase(spectrum); ``` ### Response Example ```csharp // Example output for phase array // [ 1.5708, -0.7854, 3.1416, ... ] ``` ``` -------------------------------- ### FFT.FftShift - Center Zero-Frequency Component Source: https://context7.com/swharden/fftsharp/llms.txt Rearranges FFT output so the zero-frequency (DC) component is at the center of the array, useful for visualization. ```APIDOC ## FFT.FftShift - Center Zero-Frequency Component ### Description Rearranges FFT output so the zero-frequency (DC) component is at the center of the array, which is useful for visualization and certain signal processing operations. ### Method `FFT.FftShift` ### Parameters #### Request Body - **data** (double[]) - Required - The array of FFT magnitudes or power values to be shifted. ### Response #### Success Response (200) - **shiftedData** (double[]) - The array with the zero-frequency component shifted to the center. ### Request Example ```csharp using FftSharp; using System.Numerics; double[] signal = SampleData.SampleAudio1(); Complex[] spectrum = FFT.Forward(signal); // Get magnitude with negative frequencies included double[] magnitude = FFT.Magnitude(spectrum, positiveOnly: false); // Shift so DC is at center (standard FFT visualization format) double[] shiftedMagnitude = FFT.FftShift(magnitude); ``` ### Response Example ```csharp // Example output for shiftedMagnitude array (assuming original magnitude had 1024 elements) // The element originally at index 512 (DC component) will now be at index 512. // Elements from index 0 to 511 will be shifted to the right, and elements from 513 to 1023 will be shifted to the left. ``` ``` -------------------------------- ### Apply High-Pass Frequency Filter Source: https://context7.com/swharden/fftsharp/llms.txt Silences all frequencies below a specified cutoff frequency, useful for removing DC offset and low-frequency noise. Retains frequencies above the cutoff. The filtered signal has the same length as the original. ```csharp using FftSharp; double[] signal = SampleData.SampleAudio1(); int sampleRate = 48000; // Remove all frequencies below 1000 Hz (including DC) double[] filtered = Filter.HighPass(signal, sampleRate, minFrequency: 1000); Console.WriteLine($"High-pass filtered at 1000 Hz"); ``` -------------------------------- ### Apply Low-Pass Frequency Filter Source: https://context7.com/swharden/fftsharp/llms.txt Silences all frequencies above a specified cutoff frequency using FFT-based filtering. Retains frequencies below the cutoff. The filtered signal has the same length as the original. ```csharp using FftSharp; double[] signal = SampleData.SampleAudio1(); int sampleRate = 48000; // Remove all frequencies above 2000 Hz double[] filtered = Filter.LowPass(signal, sampleRate, maxFrequency: 2000); // The filtered signal retains only frequencies <= 2000 Hz Console.WriteLine($"Original samples: {signal.Length}"); Console.WriteLine($"Filtered samples: {filtered.Length}"); ``` -------------------------------- ### Filter.BandPass - Band-Pass Frequency Filter Source: https://context7.com/swharden/fftsharp/llms.txt Retains only frequencies within a specified range, silencing everything outside the band. ```APIDOC ## Filter.BandPass - Band-Pass Frequency Filter ### Description Retains only frequencies within a specified range, silencing everything outside the band. ### Method `Filter.BandPass` ### Parameters #### Request Body - **signal** (double[]) - Required - The input time-domain signal. - **sampleRate** (int) - Required - The sample rate of the signal in Hz. - **minFrequency** (double) - Required - The lower cutoff frequency in Hz. Frequencies below this will be attenuated. - **maxFrequency** (double) - Required - The upper cutoff frequency in Hz. Frequencies above this will be attenuated. ### Response #### Success Response (200) - **filteredSignal** (double[]) - The time-domain signal with frequencies outside the specified band removed. ### Request Example ```csharp using FftSharp; double[] signal = SampleData.SampleAudio1(); int sampleRate = 48000; // Keep only frequencies between 1000 Hz and 5000 Hz double[] filtered = Filter.BandPass(signal, sampleRate, minFrequency: 1000, maxFrequency: 5000); ``` ### Response Example ```csharp // Example output for filtered signal (same length as original signal) // [ 0.0, 0.001, 0.005, ..., 0.002, 0.0 ] ``` ``` -------------------------------- ### Filter.HighPass - High-Pass Frequency Filter Source: https://context7.com/swharden/fftsharp/llms.txt Silences all frequencies below a specified cutoff frequency, useful for removing DC offset and low-frequency noise. ```APIDOC ## Filter.HighPass - High-Pass Frequency Filter ### Description Silences all frequencies below a specified cutoff frequency, useful for removing DC offset and low-frequency noise. ### Method `Filter.HighPass` ### Parameters #### Request Body - **signal** (double[]) - Required - The input time-domain signal. - **sampleRate** (int) - Required - The sample rate of the signal in Hz. - **minFrequency** (double) - Required - The cutoff frequency in Hz. Frequencies below this will be attenuated. ### Response #### Success Response (200) - **filteredSignal** (double[]) - The time-domain signal with low frequencies removed. ### Request Example ```csharp using FftSharp; double[] signal = SampleData.SampleAudio1(); int sampleRate = 48000; // Remove all frequencies below 1000 Hz (including DC) double[] filtered = Filter.HighPass(signal, sampleRate, minFrequency: 1000); ``` ### Response Example ```csharp // Example output for filtered signal (same length as original signal) // [ 0.005, 0.01, 0.008, ... ] ``` ``` -------------------------------- ### Filter.LowPass - Low-Pass Frequency Filter Source: https://context7.com/swharden/fftsharp/llms.txt Silences all frequencies above a specified cutoff frequency using FFT-based filtering. ```APIDOC ## Filter.LowPass - Low-Pass Frequency Filter ### Description Silences all frequencies above a specified cutoff frequency using FFT-based filtering. ### Method `Filter.LowPass` ### Parameters #### Request Body - **signal** (double[]) - Required - The input time-domain signal. - **sampleRate** (int) - Required - The sample rate of the signal in Hz. - **maxFrequency** (double) - Required - The cutoff frequency in Hz. Frequencies above this will be attenuated. ### Response #### Success Response (200) - **filteredSignal** (double[]) - The time-domain signal with high frequencies removed. ### Request Example ```csharp using FftSharp; double[] signal = SampleData.SampleAudio1(); int sampleRate = 48000; // Remove all frequencies above 2000 Hz double[] filtered = Filter.LowPass(signal, sampleRate, maxFrequency: 2000); ``` ### Response Example ```csharp // Example output for filtered signal (same length as original signal) // [ 0.01, 0.02, 0.015, ... ] ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.