/// <summary>
        /// Returns the smallest absolute value from the unsorted data array.
        /// Returns NaN if data is empty or any entry is NaN.
        /// </summary>
        /// <param name="data">Sample array, no sorting is assumed.</param>
        public static Complex64 MinimumMagnitudePhase(Complex64[] data)
        {
            if (data.Length == 0)
            {
                return new Complex64(double.NaN, double.NaN);
            }

            double minMagnitude = double.PositiveInfinity;
            Complex64 min = new Complex64(double.PositiveInfinity, double.PositiveInfinity);
            for (int i = 0; i < data.Length; i++)
            {
                double magnitude = data[i].Magnitude;
                if (double.IsNaN(magnitude))
                {
                    return new Complex64(double.NaN, double.NaN);
                }
                if (magnitude < minMagnitude || magnitude == minMagnitude && data[i].Phase < min.Phase)
                {
                    minMagnitude = magnitude;
                    min = data[i];
                }
            }

            return min;
        }
Example #2
0
 public static bool IsZero(this Complex64 self)
 {
     return(self.IsZero);
 }
Example #3
0
 /// <summary>
 /// Creates the collection of complex 1D kernels with the specified parameters.
 /// </summary>
 private Complex64[][] CreateComplexKernels()
 {
     var         kernels = new Complex64[KernelParameters.Length][];
     ref Vector4 baseRef = ref MemoryMarshal.GetReference(KernelParameters.AsSpan());
 public ComplexCarrierTone WithNewPhase(double newPhase) => new ComplexCarrierTone(
     frequency: frequency,
     amplitude: Complex64.FromPolarCoordinates(
         magnitude: amplitude.Magnitude,
         phase: newPhase));
 public ComplexCarrierTone(double frequency, Complex64 amplitude)
 {
     this.frequency = frequency;
     this.amplitude = amplitude;
 }
 public ComplexCarrierTone GetCarrier(double fundamentalFreq) =>
 new ComplexCarrierTone(
     frequency: fundamentalFreq * freqRatio,
     amplitude: Complex64.FromPolarCoordinates(
         magnitude: amplitude,
         phase: 2.0 * PI * CustomRandom.NextDouble()));
 public static object Multiply(long x, object other)
 {
     if (other is int)
     {
         int y = (int)other;
         try {
             return(Ops.Long2Object(checked (x * y)));
         } catch (OverflowException) {
             return(BigInteger.Create(x) * y);
         }
     }
     else if (other is BigInteger)
     {
         return(BigInteger.Create(x) * (BigInteger)other);
     }
     else if (other is double)
     {
         return(x * (double)other);
     }
     else if (other is Complex64)
     {
         return(Complex64.MakeReal(x) * (Complex64)other);
     }
     else if (other is bool)
     {
         int y = (bool)other ? 1 : 0;
         try {
             return(Ops.Long2Object(checked (x * y)));
         } catch (OverflowException) {
             return(BigInteger.Create(x) * y);
         }
     }
     else if (other is long)
     {
         long y = (long)other;
         try {
             return(checked (x * y));
         } catch (OverflowException) {
             return(BigInteger.Create(x) * y);
         }
     }
     else if (other is float)
     {
         return(x * (float)other);
     }
     else if (other is ExtensibleInt)
     {
         int y = ((ExtensibleInt)other).value;
         try {
             return(Ops.Long2Object(checked (x * y)));
         } catch (OverflowException) {
             return(BigInteger.Create(x) * y);
         }
     }
     else if (other is ExtensibleFloat)
     {
         return(x * ((ExtensibleFloat)other).value);
     }
     else if (other is ExtensibleComplex)
     {
         return(Complex64.MakeReal(x) * ((ExtensibleComplex)other).value);
     }
     else if (other is byte)
     {
         int y = (int)((byte)other);
         try {
             return(Ops.Long2Object(checked (x * y)));
         } catch (OverflowException) {
             return(BigInteger.Create(x) * y);
         }
     }
     return(Ops.NotImplemented);
 }
Example #8
0
        public static SpectralDecomp Decompose(
            IBGCStream stream,
            int windowCount   = 400,
            int windowOrder   = 12,
            int targetChannel = 0,
            double minFreq    = 0.0,
            double maxFreq    = double.PositiveInfinity)
        {
            //WindowSize is 2 ^ windowOrder
            int windowSize = 1 << windowOrder;

            if (stream.Channels <= targetChannel)
            {
                throw new ArgumentException(
                          $"TargetChannel ({targetChannel}) exceeded stream channels ({stream.Channels})",
                          nameof(targetChannel));
            }

            float[] samples = stream.IsolateChannel(targetChannel).Cache().Samples;

            int sampleOffset = (int)((samples.Length - windowSize) / (double)(windowCount - 1));

            //Adjust windowSize to conform to sample size and requirements
            while (sampleOffset <= 0 && windowOrder > 4)
            {
                --windowOrder;
                windowSize   = 1 << windowOrder;
                windowCount /= 2;
                sampleOffset = (int)((samples.Length - windowSize) / (double)(windowCount - 1));
            }

            if (windowOrder == 4)
            {
                throw new ArgumentException("Clip too short to evaluate");
            }

            if (maxFreq == double.PositiveInfinity)
            {
                //Default MaxFrequency to be determined by the size of the window
                maxFreq = FrequencyDomain.GetComplexSampleFrequency(windowSize, windowSize / 2);
            }

            //Limit Max Frquency by the size of the window
            maxFreq = Math.Min(maxFreq, FrequencyDomain.GetComplexSampleFrequency(windowSize, windowSize / 2));

            //Limit Min Frequency by the
            minFreq = Math.Max(minFreq, FrequencyDomain.GetComplexSampleFrequency(windowSize, 1));

            //Our output will be just the real-valued amplitudes
            SpectralDecomp decomp = new SpectralDecomp(minFreq, maxFreq, windowSize, windowCount);

            Complex64[] fftBuffer = new Complex64[windowSize];

            IBGCEnvelopeStream hammingWindow = new EnvelopeConcatenator(
                CosineEnvelope.HammingWindow(windowSize / 2, true),
                CosineEnvelope.HammingWindow(windowSize / 2, false));

            for (int window = 0; window < windowCount; window++)
            {
                int specificOffset = sampleOffset * window;
                hammingWindow.Reset();

                //Copy samples into buffer
                for (int i = 0; i < windowSize; i++)
                {
                    //Set real value
                    fftBuffer[i] = samples[specificOffset + i] * hammingWindow.ReadNextSample();
                }

                Fourier.Forward(fftBuffer);

                decomp.Add(window, fftBuffer);
            }

            return(decomp);
        }
Example #9
0
 public SineWave(Complex64 amplitude, double frequency)
     : this(amplitude.Magnitude, frequency, amplitude.Phase)
 {
 }
        /// <summary>
        /// Returns the largest absolute value from the unsorted data array.
        /// Returns NaN if data is empty or any entry is NaN.
        /// </summary>
        /// <param name="data">Sample array, no sorting is assumed.</param>
        public static Complex64 MaximumMagnitudePhase(Complex64[] data)
        {
            if (data.Length == 0)
            {
                return new Complex64(double.NaN, double.NaN);
            }

            double maxMagnitude = 0.0d;
            Complex64 max = Complex64.Zero;
            for (int i = 0; i < data.Length; i++)
            {
                double magnitude = data[i].Magnitude;
                if (double.IsNaN(magnitude))
                {
                    return new Complex64(double.NaN, double.NaN);
                }
                if (magnitude > maxMagnitude || magnitude == maxMagnitude && data[i].Phase > max.Phase)
                {
                    maxMagnitude = magnitude;
                    max = data[i];
                }
            }

            return max;
        }
Example #11
0
        protected override void _Initialize()
        {
            int fftBufferSize = _channelSamples.CeilingToPowerOfTwo();

            fftBuffer = new Complex64[fftBufferSize];

            double effectiveDuration = fftBufferSize / SamplingRate;

            double t_step     = effectiveDuration / (2.0 * Math.Round(maxTemporalVelocity * effectiveDuration));
            int    t_env_size = 2 * (int)Math.Round(effectiveDuration / (2.0 * t_step));

            double[] carrierFrequencies;

            switch (componentSpacing)
            {
            case ComponentSpacing.Harmonic:
            {
                int componentLB = (int)Math.Round(lowestFrequency / frequencySpacing);
                int componentUB = (int)Math.Round(lowestFrequency * Math.Pow(2, componentBandwidth) / frequencySpacing) + 1;

                int componentCount = componentUB - componentLB;
                carrierFrequencies = new double[componentCount];

                for (int n = 0; n < componentCount; n++)
                {
                    carrierFrequencies[n] = frequencySpacing * (n + componentLB);
                }
            }
            break;

            case ComponentSpacing.Log:
            {
                int componentUB = (int)(Math.Round(2 * componentBandwidth / frequencySpacing) / 2);

                carrierFrequencies = new double[componentUB];

                for (int n = 0; n < componentUB; n++)
                {
                    carrierFrequencies[n] = lowestFrequency * Math.Pow(2.0, n * frequencySpacing);
                }
            }
            break;

            default:
                UnityEngine.Debug.LogError($"Unexpected ComponentSpacing: {componentSpacing}");
                goto case ComponentSpacing.Log;
            }

            int f_env_size = carrierFrequencies.Length;

            double[] t_env_phases_sin = new double[t_env_size];
            double[] t_env_phases_cos = new double[t_env_size];

            double t_env_phase;
            double t_env_phase_factor = 2.0 * Math.PI * temporalModulationRate;

            for (int t = 0; t < t_env_size; t++)
            {
                t_env_phase         = t * t_env_phase_factor * t_step;
                t_env_phases_sin[t] = Math.Sin(t_env_phase);
                t_env_phases_cos[t] = Math.Cos(t_env_phase);
            }

            double value;
            double f_env_phase;
            double f_env_phase_factor = 2.0 * Math.PI * spectralModulationRate;
            double f_env_phase_offset = 0.5 * Math.PI;
            double f_env_phase_sin;
            double f_env_phase_cos;

            Complex64[] complexProfile = new Complex64[t_env_size];
            for (int c = 0; c < f_env_size; c++)
            {
                int f_index = (int)Math.Round(carrierFrequencies[c] * effectiveDuration);
                f_env_phase     = Math.Log(carrierFrequencies[c] / lowestFrequency, 2.0) * f_env_phase_factor + f_env_phase_offset;
                f_env_phase_sin = Math.Sin(f_env_phase);
                f_env_phase_cos = Math.Cos(f_env_phase);

                for (int t = 0; t < t_env_size; t++)
                {
                    value             = f_env_phase_sin * t_env_phases_cos[t] + f_env_phase_cos * t_env_phases_sin[t];
                    complexProfile[t] = Math.Pow(10.0, modulationDepth * value / 20.0);
                }

                Fourier.Forward(complexProfile);
                FFTShift(complexProfile);

                double componentPhase = 2.0 * Math.PI * randomizer.NextDouble();
                for (int t = 0; t < t_env_size; t++)
                {
                    complexProfile[t] *= Complex64.FromPolarCoordinates(
                        magnitude: fftBufferSize / (2.0 * t_env_size),
                        phase: componentPhase);
                }

                int leftPad  = f_index - (t_env_size / 2) - 1;
                int rightPad = (fftBufferSize / 2) - f_index - (t_env_size / 2);

                if (leftPad >= 0 && rightPad >= 0)
                {
                    for (int i = 0; i < t_env_size; i++)
                    {
                        int index = i + leftPad + 1;
                        fftBuffer[index] += complexProfile[i];
                        fftBuffer[fftBufferSize - index] += complexProfile[i].Conjugate();
                    }
                }
                else if (leftPad < 0 && rightPad > 0)
                {
                    for (int i = -leftPad; i < t_env_size; i++)
                    {
                        int index = i + leftPad + 1;
                        fftBuffer[index] += complexProfile[i];
                        fftBuffer[fftBufferSize - index] += complexProfile[i].Conjugate();
                    }
                }
                else if (leftPad > 0 && rightPad < 0)
                {
                    for (int i = 0; i < t_env_size + rightPad; i++)
                    {
                        int index = i + leftPad + 1;
                        fftBuffer[index] += complexProfile[i];
                        fftBuffer[fftBufferSize - index] += complexProfile[i].Conjugate();
                    }
                }
            }

            Fourier.Inverse(fftBuffer);
        }
Example #12
0
        public PhaseVocoder(IBGCStream stream, double speed)
            : base(stream)
        {
            baseFFTSamples     = (int)Math.Pow(2, BASE_FFT_SIZE);
            expandedFFTSamples = 2 * baseFFTSamples;
            halfFFTSamples     = baseFFTSamples / 2;

            stepSize = baseFFTSamples / OVERLAP_FACTOR;
            overlap  = baseFFTSamples - stepSize;

            outputStep    = ((int)(baseFFTSamples / speed)) / OVERLAP_FACTOR;
            outputSamples = outputStep * OVERLAP_FACTOR;

            effectiveSpeed = stepSize / (double)outputStep;

            localSampleBuffer  = new float[Channels * stepSize];
            cachedSampleBuffer = new float[Channels * outputSamples];

            phasors            = new Complex64[halfFFTSamples + 1];
            phasorDeltas       = new Complex64[halfFFTSamples + 1];
            inputBuffers       = new float[Channels][];
            outputAccumulation = new float[Channels * expandedFFTSamples];

            fftBuffer  = new Complex64[baseFFTSamples];
            ifftBuffer = new Complex64[expandedFFTSamples];

            ChannelSamples = (int)(stream.ChannelSamples / effectiveSpeed);

            for (int i = 0; i < Channels; i++)
            {
                inputBuffers[i] = new float[baseFFTSamples];
            }

            int deltaSteps = outputStep - stepSize;

            for (int i = 0; i <= halfFFTSamples; i++)
            {
                //Initialize phasors to 2 so that it doubles the amplitudes on copy and rotation
                phasors[i]      = 2f;
                phasorDeltas[i] = Complex64.FromPolarCoordinates(1.0, -i * deltaSteps / (double)baseFFTSamples);
            }

            //inputScalar = Math.Sqrt(baseFFTSamples);
            inputScalar  = 1.0;
            outputScalar = 1.0 / OVERLAP_FACTOR;

            windowInput  = new double[baseFFTSamples];
            windowOutput = new double[outputSamples];

            for (int i = 0; i < baseFFTSamples; i++)
            {
                //Hamming
                windowInput[i] = 0.54 - 0.46 * Math.Cos(2.0 * Math.PI * i / (baseFFTSamples - 1));
            }

            for (int i = 0; i < outputSamples; i++)
            {
                //Square
                windowOutput[i] = 1.0;
            }
        }
        public override int Read(float[] data, int offset, int count)
        {
            if (!initialized)
            {
                Initialize();
            }

            int samplesWritten = ReadBody(data, offset, count);

            while (samplesWritten < count)
            {
                //Slide over noise samples
                Array.Copy(
                    sourceArray: noiseBuffer,
                    sourceIndex: stepSize,
                    destinationArray: noiseBuffer,
                    destinationIndex: 0,
                    length: overlapSize);

                int read = stream.Read(inputBuffer, overlapSize, stepSize);

                if (read <= 0 && samplesHandled <= 0)
                {
                    //Done, No samples left to work with
                    break;
                }
                else if (read <= 0)
                {
                    //We are in buffer-dumping window
                    //Set rest of inputBuffer to zero
                    Array.Clear(inputBuffer, overlapSize, stepSize);
                }
                else if (read < stepSize)
                {
                    //Near or at the end
                    //Set rest of inputBuffer to zero
                    Array.Clear(inputBuffer, overlapSize + read, inputBuffer.Length - overlapSize - read);
                }

                //Generate new noise
                for (int i = 0; i < stepSize; i++)
                {
                    noiseBuffer[overlapSize + i] = noiseScalarA - noiseScalarB * randomizer.NextDouble();
                }

                //Copy in the input data
                for (int i = 0; i < fftSize; i++)
                {
                    signalFFTBuffer[i] = inputBuffer[i] * window[i];
                    noiseFFTBuffer[i]  = noiseBuffer[i];
                }

                //FFT
                Task.WaitAll(
                    Task.Run(() => Fourier.Forward(signalFFTBuffer)),
                    Task.Run(() => Fourier.Forward(noiseFFTBuffer)));

                //For each band...

                Parallel.For(
                    fromInclusive: 0,
                    toExclusive: bandFrequencies.Length - 1,
                    body: (int band) =>
                {
                    int lowerBound = FrequencyDomain.GetComplexFrequencyBin(fftSize, bandFrequencies[band], SamplingRate);
                    int upperBound = FrequencyDomain.GetComplexFrequencyBin(fftSize, bandFrequencies[band + 1], SamplingRate);

                    Complex64[] amplitudeBuffer = amplitudeBuffers[band];
                    Complex64[] noiseBandBuffer = noiseBandBuffers[band];

                    //Copy over band just the relevant frequency band
                    for (int i = lowerBound; i < upperBound; i++)
                    {
                        amplitudeBuffer[i] = 2.0 * signalFFTBuffer[i];
                        noiseBandBuffer[i] = 2.0 * noiseFFTBuffer[i];
                    }

                    Complex64 zero = Complex64.Zero;


                    //Clear rest of buffers
                    for (int i = 0; i < lowerBound; i++)
                    {
                        amplitudeBuffer[i] = zero;
                        noiseBandBuffer[i] = zero;
                    }

                    for (int i = upperBound; i < amplitudeBuffer.Length; i++)
                    {
                        amplitudeBuffer[i] = zero;
                        noiseBandBuffer[i] = zero;
                    }

                    //IFFT
                    Task.WaitAll(
                        Task.Run(() => Fourier.Inverse(amplitudeBuffer)),
                        Task.Run(() => Fourier.Inverse(noiseBandBuffer)));

                    for (int i = 0; i < amplitudeBuffer.Length; i++)
                    {
                        outputAccumulation[i] += outputFactor * window[i] * noiseBandBuffer[i].Real * amplitudeBuffer[i].Magnitude;
                    }
                });


                samplesHandled += read;

                if (--frameLag <= 0)
                {
                    bufferIndex     = 0;
                    bufferCount     = Math.Min(stepSize, samplesHandled);
                    samplesHandled -= bufferCount;

                    //Copy output samples to output buffer
                    for (int sample = 0; sample < bufferCount; sample++)
                    {
                        cachedSampleBuffer[sample] = (float)outputAccumulation[sample];
                    }
                }

                //Slide over input samples
                Array.Copy(
                    sourceArray: inputBuffer,
                    sourceIndex: stepSize,
                    destinationArray: inputBuffer,
                    destinationIndex: 0,
                    length: overlapSize);

                //Slide output samples
                Array.Copy(
                    sourceArray: outputAccumulation,
                    sourceIndex: stepSize,
                    destinationArray: outputAccumulation,
                    destinationIndex: 0,
                    length: overlapSize);

                //Clear empty output accumulation region
                Array.Clear(outputAccumulation, overlapSize, stepSize);

                samplesWritten += ReadBody(data, offset + samplesWritten, count - samplesWritten);
            }

            return(samplesWritten);
        }
        public FramedPhaseReencoder(
            IBGCStream stream,
            double timeShift,
            int frameSize     = (1 << 11),
            int overlapFactor = 8)
            : base(stream)
        {
            UnityEngine.Debug.LogWarning("FramedPhaseReencoder isn't really ready... use at your own risk.");

            this.frameSize     = frameSize;
            this.overlapFactor = overlapFactor;

            halfFrameSize = frameSize / 2;

            stepSize = frameSize / this.overlapFactor;
            overlap  = frameSize - stepSize;

            Channels = stream.Channels;

            if (stream.ChannelSamples == int.MaxValue)
            {
                TotalSamples = int.MaxValue;
            }
            else
            {
                TotalSamples = Channels * stream.ChannelSamples;
            }

            localSampleBuffer  = new float[Channels * stepSize];
            cachedSampleBuffer = new float[Channels * stepSize];

            phasors            = new Complex64[Channels][];
            inputBuffers       = new float[Channels][];
            outputAccumulation = new float[Channels * frameSize];

            fftBuffer = new Complex64[frameSize];

            timeShifts = Enumerable.Repeat(timeShift, Channels).ToArray();
            for (int i = 0; i < Channels; i++)
            {
                inputBuffers[i] = new float[frameSize];

                double rotationFactor = -2.0 * PI * SamplingRate * timeShifts[i] / frameSize;
                for (int j = 1; j < halfFrameSize; j++)
                {
                    //Initialize phasors to 2 so that it doubles the amplitudes on copy and rotation
                    phasors[i][j] = Complex64.FromPolarCoordinates(2.0, j * rotationFactor);
                }

                phasors[i][0] = 1.0;
            }

            outputScalar = 1.0 / (this.overlapFactor);

            windowInput = new double[frameSize];

            for (int i = 0; i < frameSize; i++)
            {
                //Hamming
                windowInput[i] = 0.54 - 0.46 * Cos(2.0 * PI * i / (frameSize - 1));
            }
        }
Example #15
0
 private static object TrueDivide(Complex64 x, Complex64 y)
 {
     return(x / y);
 }
Example #16
0
 void WriteComplex(Complex64 val)
 {
     bytes.Add((byte)'x');
     WriteDoubleString(val.real);
     WriteDoubleString(val.imag);
 }
Example #17
0
 public static object Abs(Complex64 x)
 {
     return(x.Abs());
 }
Example #18
0
 private static object TrueDivide(int x, Complex64 y)
 {
     return(ComplexOps.TrueDivide(Complex64.MakeReal(x), y));
 }
Example #19
0
 public ExtensibleComplex()
 {
     this.value = new Complex64();
 }
        public static object Mod(long x, object other)
        {
            if (other is int)
            {
                int y = (int)other;
                try {
                    return(Ops.Long2Object(Mod(x, y)));
                } catch (OverflowException) {
                    return(BigInteger.Create(x) % y);
                }
            }
            else if (other is BigInteger)
            {
                return(LongOps.Mod(BigInteger.Create(x), (BigInteger)other));
            }
            else if (other is double)
            {
                return(FloatOps.Mod(x, (double)other));
            }
            else if (other is Complex64)
            {
                return(ComplexOps.Mod(Complex64.MakeReal(x), (Complex64)other));
            }
            else if (other is bool)
            {
                int y = (bool)other ? 1 : 0;
                try {
                    return(Ops.Long2Object(Mod(x, y)));
                } catch (OverflowException) {
                    return(BigInteger.Create(x) % y);
                }
            }
            else if (other is long)
            {
                long y = (long)other;
                try {
                    return(Mod(x, y));
                } catch (OverflowException) {
                    return(BigInteger.Create(x) % y);
                }
            }
            else if (other is float)
            {
                return(FloatOps.Mod(x, (float)other));
            }
            else if (other is ExtensibleInt)
            {
                int y = ((ExtensibleInt)other).value;
                try {
                    return(Ops.Long2Object(Mod(x, y)));
                } catch (OverflowException) {
                    return(BigInteger.Create(x) % y);
                }
            }
            else if (other is ExtensibleFloat)
            {
                return(FloatOps.Mod(x, ((ExtensibleFloat)other).value));
            }
            else if (other is ExtensibleComplex)
            {
                return(ComplexOps.Mod(Complex64.MakeReal(x), ((ExtensibleComplex)other).value));
            }
            else if (other is byte)
            {
                int y = (int)((byte)other);
                try {
                    return(Ops.Long2Object(Mod(x, y)));
                } catch (OverflowException) {
                    return(BigInteger.Create(x) % y);
                }
            }

            return(Ops.NotImplemented);
        }
Example #21
0
 public ExtensibleComplex(double real)
 {
     value = new Complex64(real);
 }
        public FrequencyModulationFilter(
            IBGCStream stream,
            double modRate,
            double modDepth)
            : base(stream)
        {
            if (stream.Channels != 1)
            {
                throw new StreamCompositionException(
                          $"FrequencyModulationFilter requires a mono input stream.  Input stream has {stream.Channels} channels");
            }

            double[] realConvolutionFilter = new double[FILTER_LENGTH];
            double[] imagConvolutionFilter = new double[FILTER_LENGTH];

            const double twoPiSq = 2f * PI * PI;
            const double fourASq = 4f * A * A;
            const double piSq    = PI * PI;
            const double piOv4   = PI / 4f;
            const double piOv4A  = PI / (4f * A);
            double       N_0     = (FILTER_LENGTH - 1.0) / 2.0;

            for (int i = 1; i < FILTER_LENGTH - 1; i++)
            {
                if (i == N_0)
                {
                    continue;
                }

                double t         = 2 * PI * (i - N_0);
                double prefactor = twoPiSq * Cos(A * t) / (t * (fourASq * t * t - piSq));

                realConvolutionFilter[i] = prefactor * (Sin(W_1 * t + piOv4) - Sin(W_2 * t + piOv4));
            }

            realConvolutionFilter[0] = A * (Sin(piOv4A * (A - 2f * W_1)) - Sin(piOv4A * (A - 2f * W_2)));
            realConvolutionFilter[FILTER_LENGTH - 1] = A * (Sin(piOv4A * (A + 2f * W_2)) - Sin(piOv4A * (A + 2f * W_1)));

            if (FILTER_LENGTH % 2 == 1)
            {
                realConvolutionFilter[(int)N_0] = Sqrt(2f) * (W_2 - W_1);
            }

            for (int i = 0; i < FILTER_LENGTH; i++)
            {
                imagConvolutionFilter[i] = realConvolutionFilter[FILTER_LENGTH - 1 - i];
            }

            convStream = new MultiConvolutionFilter(stream, realConvolutionFilter, imagConvolutionFilter);

            modulatorPeriodSamples = (int)Abs(Round(SamplingRate / modRate));
            modRate = Sign(modRate) * SamplingRate / (double)modulatorPeriodSamples;

            modulator = new Complex64[modulatorPeriodSamples];

            for (int i = 0; i < modulatorPeriodSamples; i++)
            {
                modulator[i] = Complex64.FromPolarCoordinates(
                    magnitude: 1.0,
                    phase: (modDepth / modRate) * Sin(2.0 * PI * i / modulatorPeriodSamples));
            }
        }
Example #23
0
        /// <summary>
        /// Used when user calls cmp(x,y) versus x > y, if the values are the same we return 0.
        /// </summary>
        public static int TrueCompare(object x, object y)
        {
            // Complex vs. null is 1 (when complex is on the lhs)
            // Complex vs. another type is -1 (when complex is on the lhs)
            // If two complex values are equal we return 0
            // Otherwise we throw because it's an un-ordered comparison
            if (x is Complex64)
            {
                Complex64 us = (Complex64)x;

                // Complex vs null, 1
                if (y == null)
                {
                    return(1);
                }

                // Compex vs Complex, if they're equal we return 0, otherwize we throw
                Complex64 them      = new Complex64();
                bool      haveOther = false;
                if (y is Complex64)
                {
                    them      = (Complex64)y;
                    haveOther = true;
                }
                else if (y is ExtensibleComplex)
                {
                    them      = ((ExtensibleComplex)y).value;
                    haveOther = true;
                }
                else
                {
                    object res = Ops.GetDynamicType(y).Coerce(y, x);
                    if (res != Ops.NotImplemented && !(res is OldInstance))
                    {
                        return(Ops.Compare(((Tuple)res)[1], ((Tuple)res)[0]));
                    }
                }


                if (haveOther)
                {
                    if (us.imag == them.imag && us.real == them.real)
                    {
                        return(0);
                    }
                    throw Ops.TypeError("complex is not an ordered type");
                }

                // Complex vs user type, check what the user type says
                object ret = Ops.GetDynamicType(y).CompareTo(y, x);
                if (ret != Ops.NotImplemented)
                {
                    return(((int)ret) * -1);
                }

                // Otherwise all types are less than complex
                return(-1);
            }
            else
            {
                System.Diagnostics.Debug.Assert(y is Complex64);
                return(-1 * TrueCompare(y, x));
            }
        }
 public ComplexCarrierTone(double frequency)
 {
     this.frequency = frequency;
     amplitude      = 1.0;
 }
Example #25
0
 public ExtensibleComplex(double real, double imag)
 {
     value = new Complex64(real, imag);
 }
Example #26
0
 public static Fraction Hypot(Fraction x1, Fraction y1)
 {
     return(Complex64.Hypot((double)x1, (double)y1));
 }
Example #27
0
 public static object Negate(Complex64 x)
 {
     return(-x);
 }
Example #28
0
 public static double Imaginary(this Complex64 self)
 {
     return(self.Imag);
 }
Example #29
0
 public static Complex64 Conjugate(Complex64 x)
 {
     return(x.Conjugate());
 }
Example #30
0
 public static Complex64 Pow(this Complex64 self, Complex64 power)
 {
     return(self.Power(power));
 }
Example #31
0
        public static object Make(
            PythonType cls,
            [DefaultParameterValueAttribute(null)] object real,
            [DefaultParameterValueAttribute(null)] object imag
            )
        {
            Conversion conv;
            Complex64  real2, imag2;

            real2 = imag2 = new Complex64();

            if (imag != null)
            {
                if (real is string)
                {
                    throw Ops.TypeError("complex() can't take second arg if first is a string");
                }
                if (imag is string)
                {
                    throw Ops.TypeError("complex() second arg can't be a string");
                }
                imag2 = Converter.TryConvertToComplex64(imag, out conv);
                if (conv == Conversion.None)
                {
                    throw Ops.TypeError("complex() argument must be a string or a number");
                }
            }

            if (real != null)
            {
                if (real is string)
                {
                    real2 = LiteralParser.ParseComplex64((string)real);
                }
                else if (real is Complex64)
                {
                    if (imag == null && cls == ComplexType)
                    {
                        return(real);
                    }
                    else
                    {
                        real2 = (Complex64)real;
                    }
                }
                else
                {
                    real2 = Converter.TryConvertToComplex64(real, out conv);
                    if (conv == Conversion.None)
                    {
                        throw Ops.TypeError("complex() argument must be a string or a number");
                    }
                }
            }

            Complex64 c = real2 + imag2 * Complex64.MakeImaginary(1);

            if (cls == ComplexType)
            {
                return(new Complex64(c.real, c.imag));
            }
            else
            {
                return(cls.ctor.Call(cls, c.real, c.imag));
            }
        }
        /// <summary>
        /// Returns the smallest absolute value from the enumerable, in a single pass without memoization.
        /// Returns NaN if data is empty or any entry is NaN.
        /// </summary>
        /// <param name="stream">Sample stream, no sorting is assumed.</param>
        public static Complex64 MinimumMagnitudePhase(IEnumerable<Complex64> stream)
        {
            double minMagnitude = double.PositiveInfinity;
            Complex64 min = new Complex64(double.PositiveInfinity, double.PositiveInfinity);
            bool any = false;

            foreach (var d in stream)
            {
                double magnitude = d.Magnitude;
                if (double.IsNaN(magnitude))
                {
                    return new Complex64(double.NaN, double.NaN);
                }
                if (magnitude < minMagnitude || magnitude == minMagnitude && d.Phase < min.Phase)
                {
                    minMagnitude = magnitude;
                    min = d;
                }

                any = true;
            }

            return any ? min : new Complex64(double.NaN, double.NaN);
        }
 public static object Mod(int x, object other)
 {
     if (other is int)
     {
         int y = (int)other;
         try {
             return(Ops.Int2Object(Mod(x, y)));
         } catch (OverflowException) {
             return(LongOps.Mod(BigInteger.Create(x), y));
         }
     }
     else if (other is BigInteger)
     {
         return(LongOps.Mod(BigInteger.Create(x), (BigInteger)other));
     }
     else if (other is double)
     {
         return(FloatOps.Mod(x, (double)other));
     }
     else if (other is Complex64)
     {
         Complex64 y = (Complex64)other;
         if (y.IsZero)
         {
             throw Ops.ZeroDivisionError();
         }
         return(ComplexOps.Mod(Complex64.MakeReal(x), y));
     }
     else if (other is bool)
     {
         bool b = (bool)other;
         return(x % (b ? 1 : 0));
     }
     else if (other is long)
     {
         long y = (long)other;
         try {
             return(Mod(x, y));
         } catch (OverflowException) {
             return(LongOps.Mod(BigInteger.Create(x), y));
         }
     }
     else if (other is float)
     {
         return(FloatOps.Mod(x, (float)other));
     }
     else if (other is byte)
     {
         return(Ops.Int2Object(Mod(x, (int)((byte)other))));
     }
     else if (other is ExtensibleInt)
     {
         int y = ((ExtensibleInt)other).value;
         try {
             return(Ops.Int2Object(Mod(x, y)));
         } catch (OverflowException) {
             return(LongOps.Mod(BigInteger.Create(x), y));
         }
     }
     else if (other is ExtensibleFloat)
     {
         return(FloatOps.Mod(x, ((ExtensibleFloat)other).value));
     }
     else if (other is ExtensibleComplex)
     {
         Complex64 y = ((ExtensibleComplex)other).value;
         if (y.IsZero)
         {
             throw Ops.ZeroDivisionError();
         }
         return(ComplexOps.Mod(Complex64.MakeReal(x), y));
     }
     return(Ops.NotImplemented);
 }