예제 #1
0
 //b == Cosh(a)
 //c == Sinh(a)
 public static void CoshSinh(Complex a, out Complex b, out Complex c)
 {
     Complex d, e;
     Exp(a, out d, out e);
     b = (d + e) / 2;
     c = (d - e) / 2;
 }
예제 #2
0
        // compute the FFT of x[], assuming its length is a power of 2
        public static Complex[] fft(Complex[] x)
        {
            int N = x.Length;

            // base case
            if (N == 1) return new Complex[] { x[0] };

            // radix 2 Cooley-Tukey FFT
            if (N % 2 != 0) { throw new Exception("N is not a power of 2"); }

            // fft of even terms
            Complex[] even = new Complex[N/2];
            for (int k = 0; k < N/2; k++) {
                even[k] = x[2*k];
            }
            Complex[] q = fft(even);

            // fft of odd terms
            Complex[] odd  = even;  // reuse the array
            for (int k = 0; k < N/2; k++) {
                odd[k] = x[2*k + 1];
            }
            Complex[] r = fft(odd);

            // combine
            Complex[] y = new Complex[N];
            for (int k = 0; k < N/2; k++) {
                double kth = -2 * k * Math.PI / N;
                Complex wk = new Complex(Math.Cos(kth), Math.Sin(kth));
                Complex tmp = wk * r[k];
                y[k]       = q[k] + tmp;
                y[k + N/2] = q[k] - tmp;
            }
            return y;
        }
예제 #3
0
        public static Complex[] FFT(float[] samples)
        {
            //Debug.Assert((samples.Length & (samples.Length - 1)) == 0);
            //FIXME: what happens if I pass non power of 2??

            #if false
            Func<int, int, double> window_fn = FastFourierTransform.HammingWindow;
            #else
            Func<int, int, double> window_fn = (a, b) => 1;
            #endif

            Complex[] fftData = new Complex[samples.Length];
            for (int i = 0; i < samples.Length; ++i)
            {
                fftData[i].X = (float) (samples[i] * window_fn(i, samples.Length));
                fftData[i].Y = 0;
            }

            /* in-place, forwards FFT.
             * Input is a sequence of complex numbers with sample amplitude in the real part and a 0 imaginary part.
             * Output is a sequence of complex numbers, whose modulus is the amplitude at that frequency.
             * Outputs range in frequency from 0 to sample rate
             */
            FastFourierTransform.FFT(true, (int) Math.Log(fftData.Length, 2), fftData);

            return fftData;
        }
예제 #4
0
 //b == Exp(a)
 //c == 1/Exp(a)
 public static void Exp(Complex a, out Complex b, out Complex c)
 {
     double d = Math.Exp(a.Real);
     Complex e = new Complex(Math.Cos(a.Imaginary), Math.Sin(a.Imaginary));
     b = e * d;
     c = b.Reciprocal();
 }
예제 #5
0
 public override void addOpperand(Calc calc,Complex c)
 {
     //calc.Opperand1=calc.Total;
     //calc.Opperand2=c;
     calc.Total=c;
     calc.CurrentState=OpperandEnteredState.Singleton;
 }
예제 #6
0
        /// <summary>
        /// Computes an Fast Fourier Transform.
        /// </summary>
        /// <param name="data">Array of complex numbers. This array provides the input data and is used to store the result of the FFT.</param>
        /// <param name="exponent">The exponent n.</param>
        /// <param name="mode">The <see cref="FftMode"/> to use. Use <see cref="FftMode.Forward"/> as the default value.</param>
        public static void Fft(Complex[] data, int exponent, FftMode mode = FftMode.Forward)
        {
            //count; if exponent = 12 -> c = 2^12 = 4096
            int c = (int)Math.Pow(2, exponent);

            //binary inversion
            Inverse(data, c);

            int j0, j1, j2 = 1;
            float n0, n1, tr, ti, m;
            float v0 = -1, v1 = 0;

            //move to outer scope to optimize performance
            int j, i;

            for (int l = 0; l < exponent; l++)
            {
                n0 = 1;
                n1 = 0;
                j1 = j2;
                j2 <<= 1; //j2 * 2

                for (j = 0; j < j1; j++)
                {
                    for (i = j; i < c; i += j2)
                    {
                        j0 = i + j1;
                        //--
                        tr = n0 * data[j0].Real - n1 * data[j0].Imaginary;
                        ti = n0 * data[j0].Imaginary + n1 * data[j0].Real;
                        //--
                        data[j0].Real = data[i].Real - tr;
                        data[j0].Imaginary = data[i].Imaginary - ti;
                        //add
                        data[i].Real += tr;
                        data[i].Imaginary += ti;
                    }

                    //calc coeff
                    m = v0 * n0 - v1 * n1;
                    n1 = v1 * n0 + v0 * n1;
                    n0 = m;
                }

                if (mode == FftMode.Forward)
                {
                    v1 = (float)Math.Sqrt((1f - v0) / 2f);
                }
                else
                {
                    v1 = (float)-Math.Sqrt((1f - v0) / 2f);
                }
                v0 = (float)Math.Sqrt((1f + v0) / 2f);
            }

            if (mode == FftMode.Forward)
            {
                Forward(data, c);
            }
        }
예제 #7
0
		public static Complex Tanh(Complex z)
		{
			double x = Math.Tanh(z.Re);
			double y = Math.Tan(z.Im);

			return new Complex(x, y) / new Complex(1, x * y);
		}
예제 #8
0
        public Complex response(double freq)
        {
            int i;
            Complex rnum = 0;
            Complex rden = 0;
            Complex[] omega = new Complex[s.Length];
            Complex z = Complex.Exp(new Complex(0, 2 * Math.PI * freq));
            omega[0] = 1.0;
            omega[1] = z;

            for (i = 2; i < s.Length; i++)
                omega[i] = omega[i - 1] * z;

            for (i = 0; i < a.Length; i++)
                rnum += a[i] * omega[i];

            rden = omega[0];
            for (i = 1; i < b.Length; i++)
                rden += b[i] * omega[i];

            if (rden.Magnitude == 0)
            {
                return Double.MaxValue;
            }
            else
            {
                return rnum / rden;
            }
        }
예제 #9
0
 public Hash(Complex[][] comData)
 {
     this.comData = comData;
     width = comData.Length;
     if (width != 0)
         height = 600;
 }
        public static void RunTests_BoundaryValues()
        {
            // Verify test results with Max
            Complex max = new Complex(double.MaxValue, double.MaxValue);

            Complex complexExp = Complex.Exp(max);
            Support.VerifyRealImaginaryProperties(complexExp, Math.Cos(double.MaxValue) * double.PositiveInfinity, double.PositiveInfinity,
                string.Format("Exp(Max) is not (Infinity, Infinity)"));

            // Verify test results with MaxReal
            Complex maxReal = new Complex(double.MaxValue, 0.0);

            complexExp = Complex.Exp(max);
            Support.VerifyRealImaginaryProperties(complexExp, Math.Cos(double.MaxValue) * double.PositiveInfinity, double.PositiveInfinity, 
                string.Format("Exp(MaxReal) is not (Infinity, Infinity))"));

            // Verify test results with MaxImg
            VerifyExpWithAddition(0.0, double.MaxValue);

            // Verify test results with Min
            VerifyExpWithAddition(double.MinValue, double.MinValue);

            // Verify test results with MinReal
            VerifyExpWithAddition(double.MinValue, 0.0);

            // Verify test results with MinImaginary
            VerifyExpWithAddition(0.0, double.MinValue);
        }
 public JuliaWithClouds(ulong IterCount, double LeftEdge, double RightEdge, double TopEdge, double BottomEdge, Complex ComplexConst,int MaxAmmountAtTrace=100,int AbcissStepSize=20,int OrdinateStepSize=20)
     : base(IterCount,LeftEdge,RightEdge,TopEdge,BottomEdge,ComplexConst)
 {
     _max_ammount_at_trace = MaxAmmountAtTrace;
     _abciss_step_length = AbcissStepSize;
     _ordinate_step_length = OrdinateStepSize;
 }
예제 #12
0
 /// <summary>
 /// Clamp elements in the complex array to range [minimum,maximum]
 /// </summary>
 /// <param name="array"></param>
 /// <param name="minimum"></param>
 /// <param name="maximum"></param>
 public static void Clamp( Complex[] array, Complex minimum, Complex maximum )
 {
     for( int i = 0; i < array.Length; i ++ ) {
         array[i].Re	= Math.Min( Math.Max( array[ i ].Re, minimum.Re ), maximum.Re );
         array[i].Im	= Math.Min( Math.Max( array[ i ].Re, minimum.Im ), maximum.Im );
     }
 }
예제 #13
0
        private static void VerifyFactoryMethod(double magnitude, double phase)
        {
            double m = magnitude;
            double p = phase;
            Complex c_new = Complex.FromPolarCoordinates(magnitude, phase);
            //Double.IsNaN(magnitude) is checked in the verifiation method.
            if (Double.IsNaN(phase) || Double.IsInfinity(phase))
            {
                magnitude = Double.NaN;
                phase = Double.NaN;
            }
            // Special check in Complex.Abs method
            else if (Double.IsInfinity(magnitude))
            {
                magnitude = Double.PositiveInfinity;
                phase = Double.NaN;
            }

            if (false == Support.VerifyMagnitudePhaseProperties(c_new, magnitude, phase))
            {
                Console.WriteLine("Error_89fdl!!! FromPolorCoordinates: ({0}, {1})", m, p);

                Assert.True(false, "Verification Failed");
            }
            else // if the first verification returns TrUe, do the second one!
            {
                Complex c_new_ctor = new Complex(c_new.Real, c_new.Imaginary);
                if (false == Support.VerifyMagnitudePhaseProperties(c_new_ctor, magnitude, phase))
                {
                    Console.WriteLine("Error_fs46!!! FromPolorCoordinates: ({0}, {1})", m, p);

                    Assert.True(false, "Verification Failed");
                }
            }
        }
예제 #14
0
    }//multiply

    public cFloat divide(cFloat c1, cFloat c2){
      Complex comp1 = new Complex(c1.getReal(), c1.getImg());
      Complex comp2 = new Complex(c2.getReal(), c1.getImg());
      Complex comp3 = comp1 / comp2;

      return new cFloat((float)comp3.Real, (float)comp3.Imaginary);
    }//divide
예제 #15
0
파일: Task4.cs 프로젝트: annhv/parp
        public static void Start(Random rnd)
        {
            int length = 4096;
            var masComplex1 = new Complex[length];
            var masSimdComplex1 = new Vector2[length];
            var masComplex2 = new Complex[length];
            var masSimdComplex2 = new Vector2[length];
            for (int i = 0; i < length; i++)
            {
                float v1 = (float) rnd.NextDouble()*1000;
                float v2 = (float) rnd.NextDouble()*1000;
                masComplex1[i] = new Complex(v1, v2);
                masSimdComplex1[i] = new Vector2(v1,v2);

                v1 = (float)rnd.NextDouble() * 1000;
                v2 = (float)rnd.NextDouble() * 1000;
                masComplex2[i] = new Complex(v1, v2);
                masSimdComplex2[i] = new Vector2(v1, v2);
            }

            Extensions.TestTime(() =>
                TestWithoutSimd(masComplex1, masComplex2),
                "Время для complex       ");

            Extensions.TestTime(() =>
                TestWithSimd(masSimdComplex1, masSimdComplex2),
                "Время для complex(simd) ");
        }
예제 #16
0
        public void Update(Complex[] fftResults)
        {
            // no need to repaint too many frames per second
            if (updateCount++ % 2 == 0)
            {
                return;
            }

            if (fftResults.Length / 2 != bins)
            {
                this.bins = fftResults.Length / 2;
                CalculateXScale();
            }

            for (int n = 0; n < fftResults.Length / 2; n+= binsPerPoint)
            {
                // averaging out bins
                double yPos = 0;
                for (int b = 0; b < binsPerPoint; b++)
                {
                    yPos += GetYPosLog(fftResults[n+b]);
                }
                AddResult(n / binsPerPoint, yPos / binsPerPoint);
            }
        }
예제 #17
0
        public void processData(ref Complex[][] res, ref int resLen)
        {
            resLen = 0;

            int channels = 2;
            int pbs = 4096*2*channels;

            for(int i = 0; i<len/pbs; i++)
            {

                comData = new Complex[10000];
                comLen = 0;

                for (int j = i*pbs, cur = 0; j < (i+1)*pbs; j+=2*channels, cur++)
                {
                    float sum = 0;
                    for (int k = 0; k < channels; k++)
                        sum += (buf[j + 2 * k + 1] << 8) | (buf[j + 2 * k]);
                    sum /= channels;
                    comData[comLen].X = sum;
                    comData[comLen].X *= (float)FastFourierTransform.HammingWindow(cur, 4096);
                    comData[comLen].Y = 0;
                    comLen++;
                }

                FastFourierTransform.FFT(true, 12, comData);

                res[resLen] = comData;
                resLen++;
            }
            resLen++;
            resLen--;
        }
예제 #18
0
        public void ToStringTest()
        {
            var complex = new Complex(3.1, 2.5);
            var exp = new Reciprocal(new ComplexNumber(complex));

            Assert.Equal("reciprocal(3.1+2.5i)", exp.ToString());
        }
        public override void AddVectorToScaledVector(Complex[] y, Complex alpha, Complex[] x, Complex[] result)
        {
            if (y == null)
            {
                throw new ArgumentNullException("y");
            }

            if (x == null)
            {
                throw new ArgumentNullException("x");
            }

            if (y.Length != x.Length)
            {
                throw new ArgumentException(Resources.ArgumentVectorsSameLength);
            }

            if (!ReferenceEquals(y, result))
            {
                Array.Copy(y, 0, result, 0, y.Length);
            }

            if (alpha == Complex.Zero)
            {
                return;
            }

            SafeNativeMethods.z_axpy(y.Length, alpha, x, result);
        }
        private static void VerifySqrtWithRectangularForm(Double real, Double imaginary)
        {
            // sqrt(a+bi) = +- (sqrt(r + a) + i sqrt(r - a) sign(b)) sqrt(2) / 2, unless a=-r and y = 0
            Complex complex = new Complex(real, imaginary);

            Double expectedReal = 0.0;
            Double expectedImaginary = 0.0;

            if (0 == imaginary)
            {
                if (real == -complex.Magnitude)
                    expectedImaginary = Math.Sqrt(-real);
                else
                    expectedReal = Math.Sqrt(real);
            }
            else
            {
                Double scale = 1 / Math.Sqrt(2);
                expectedReal = scale * Math.Sqrt(complex.Magnitude + complex.Real);
                expectedImaginary = scale * Math.Sqrt(complex.Magnitude - complex.Real);
                if (complex.Imaginary < 0)
                {
                    expectedImaginary = -expectedImaginary;
                }
            }
            VerifySqrtWithRectangularForm(real, imaginary, expectedReal, expectedImaginary);
        }
예제 #21
0
        public void ExecuteTest1()
        {
            var complex = new Complex(3.1, 2.5);
            var exp = new Reciprocal(new ComplexNumber(complex));

            Assert.Equal(Complex.Reciprocal(complex), exp.Execute());
        }
        /// <summary>
        /// Gets the correlation.
        /// </summary>
        /// <param name="originalVector">The original vector.</param>
        /// <param name="correlationVector">The correlation vector.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentException">Different length of vectors</exception>
        public static Complex[] GetCorrelation(Complex[] originalVector, Complex[] correlationVector)
        {
            if (originalVector.Length != correlationVector.Length)
            {
                throw new ArgumentException("Different length of vectors");
            }

            CorrelationComplexibility = 0;

            // ReSharper disable once InconsistentNaming
            var N = originalVector.Length;
            var result = new Complex[N];

            for (var i = 0; i < N; i++)
            {
                for (var j = 0; j < N; j++)
                {
                    if (i + j < N)
                    {
                        result[i] += originalVector[j] * correlationVector[i + j];
                        CorrelationComplexibility++;
                    }
                    else
                    {
                        result[i] += originalVector[j] * correlationVector[i + j - N];
                        CorrelationComplexibility++;
                    }
                }

                result[i] /= N;
            }

            return result;
        }
 //---------------------------------------------------------------------------------------------
 /// <summary>
 ///   Clamp length (modulus) of the elements in the complex array
 /// </summary>
 /// <param name = "array"></param>
 /// <param name = "fMinimum"></param>
 /// <param name = "fMaximum"></param>
 public static void ClampLength(Complex[] array, double fMinimum, double fMaximum)
 {
     for (int i = 0; i < array.Length; i++)
     {
         array[i] = Complex.FromModulusArgument(Math.Max(fMinimum, Math.Min(fMaximum, array[i].GetModulus())), array[i].GetArgument());
     }
 }
예제 #24
0
        public static Complex operator +(Complex c1, Complex c2)
        {
            int cnt = c1.b * c2.b;
            int sum = c2.b * c1.a + c1.b * c2.a;
            if (cnt > sum)
            {
                for (int i = sum; i > 2; i--)
                {
                    if (cnt % i == 0 && sum % i == 0)
                    {
                        cnt = cnt / i;
                        sum = sum / i;
                        break;
                    }
                }
            }
            else
            {
                for (int i = cnt; i > 2; i--)
                {
                    if (cnt % i == 0 && sum % i == 0)
                    {
                        cnt = cnt / i;
                        sum = sum / i;
                        break;
                    }

                }
            }
            Complex c3 = new Complex(sum, cnt);
            return c3;
        }
예제 #25
0
파일: Program.cs 프로젝트: HoreaOros/Cosmin
        static void Main(string[] args)
        {
            Complex c1 = new Complex(1, 2);
            Complex c2 = new Complex(1, 2);
            Complex c3 = new Complex();

            Console.WriteLine(c1);
            Console.WriteLine(c2);
            Console.WriteLine(c3);

            Complex c4 = c1.Add(c2);
            Console.WriteLine(c4);

            Complex c5 = c2.Subtract(c1);
            Console.WriteLine(c5);

            Complex c6 = c1.Multiply(c2);
            Console.WriteLine(c6);

                      
            if(c1.Equals(c2))
                Console.WriteLine("c1 este egal cu c2");
            else
                Console.WriteLine("c1 nu este egal cu c2");

        }
예제 #26
0
        public void ExecuteWithParamsTest()
        {
            var complex = new Complex(5, 2);
            var exp = new ComplexNumber(complex);

            Assert.Equal(complex, exp.Execute(null));
        }
예제 #27
0
 public void SetVar(string varname, Complex value)
 {
     var root = Root;
     if (root.m_variables == null)
         root.m_variables = new Dictionary<string, Complex>();
     root.m_variables[varname.ToLower()] = value;
 }
예제 #28
0
        /// <summary>
        /// Initializes a new instance of the <see cref="UserQR"/> class. This object will compute the
        /// QR factorization when the constructor is called and cache it's factorization.
        /// </summary>
        /// <param name="matrix">The matrix to factor.</param>
        /// <param name="method">The QR factorization method to use.</param>
        /// <exception cref="ArgumentNullException">If <paramref name="matrix"/> is <c>null</c>.</exception>
        public static UserQR Create(Matrix<Complex> matrix, QRMethod method = QRMethod.Full)
        {
            if (matrix.RowCount < matrix.ColumnCount)
            {
                throw Matrix.DimensionsDontMatch<ArgumentException>(matrix);
            }

            Matrix<Complex> q;
            Matrix<Complex> r;

            var minmn = Math.Min(matrix.RowCount, matrix.ColumnCount);
            var u = new Complex[minmn][];

            if (method == QRMethod.Full)
            {
                r = matrix.Clone();
                q = Matrix<Complex>.Build.SameAs(matrix, matrix.RowCount, matrix.RowCount);

                for (var i = 0; i < matrix.RowCount; i++)
                {
                    q.At(i, i, 1.0f);
                }

                for (var i = 0; i < minmn; i++)
                {
                    u[i] = GenerateColumn(r, i, i);
                    ComputeQR(u[i], r, i, matrix.RowCount, i + 1, matrix.ColumnCount, Control.MaxDegreeOfParallelism);
                }

                for (var i = minmn - 1; i >= 0; i--)
                {
                    ComputeQR(u[i], q, i, matrix.RowCount, i, matrix.RowCount, Control.MaxDegreeOfParallelism);
                }
            }
            else
            {
                q = matrix.Clone();

                for (var i = 0; i < minmn; i++)
                {
                    u[i] = GenerateColumn(q, i, i);
                    ComputeQR(u[i], q, i, matrix.RowCount, i + 1, matrix.ColumnCount, Control.MaxDegreeOfParallelism);
                }

                r = q.SubMatrix(0, matrix.ColumnCount, 0, matrix.ColumnCount);
                q.Clear();

                for (var i = 0; i < matrix.ColumnCount; i++)
                {
                    q.At(i, i, 1.0f);
                }

                for (var i = minmn - 1; i >= 0; i--)
                {
                    ComputeQR(u[i], q, i, matrix.RowCount, i, matrix.ColumnCount, Control.MaxDegreeOfParallelism);
                }
            }

            return new UserQR(q, r, method);
        }
예제 #29
0
        public void ExecuteTest()
        {
            var complex = new Complex(5, 2);
            var exp = new ComplexNumber(complex);

            Assert.Equal(complex, exp.Execute());
        }
        private static void VerifyBinaryMultiplyResult(Double realFirst, Double imgFirst, Double realSecond, Double imgSecond)
        {
            // calculate the expected results
            Double realExpectedResult = realFirst * realSecond - imgFirst * imgSecond;
            Double imaginaryExpectedResult = realFirst * imgSecond + imgFirst * realSecond;

            // Create complex numbers
            Complex cFirst = new Complex(realFirst, imgFirst);
            Complex cSecond = new Complex(realSecond, imgSecond);

            // arithmetic multiply (binary) operation
            Complex cResult = cFirst * cSecond;

            // verify the result
            if (false == Support.VerifyRealImaginaryProperties(cResult, realExpectedResult, imaginaryExpectedResult))
            {
                Console.WriteLine("ErRoR! Binary Multiply Error!");
                Console.WriteLine("Binary Multiply test = ({0}, {1}) * ({2}, {3})", realFirst, imgFirst, realSecond, imgSecond);
                Assert.True(false, "Verification Failed");
            }

            // arithmetic multiply (static) operation
            cResult = Complex.Multiply(cFirst, cSecond);

            // verify the result
            if (false == Support.VerifyRealImaginaryProperties(cResult, realExpectedResult, imaginaryExpectedResult))
            {
                Console.WriteLine("ErRoR! Multiply (Static) Error!");
                Console.WriteLine("Multiply (Static) test = ({0}, {1}) * ({2}, {3})", realFirst, imgFirst, realSecond, imgSecond);
                Assert.True(false, "Verification Failed");
            }
        }
 private static Complex Sin(Complex[] args) => Complex.Sin(args.Check(1)[0]);
 // Two-argument functions
 private static Complex Pow(Complex[] args)
 {
     args.Check(2); return(Complex.Pow(args[0], args[1]));
 }
 private static Complex Exp(Complex[] args) => Complex.Exp(args.Check(1)[0]);
 private static Complex Tanh(Complex[] args) => Complex.Tanh(args.Check(1)[0]);
 private static Complex Cosh(Complex[] args) => Complex.Cosh(args.Check(1)[0]);
 private static Complex Atan(Complex[] args) => Complex.Atan(args.Check(1)[0]);
 private static Complex Acos(Complex[] args) => Complex.Acos(args.Check(1)[0]);
예제 #38
0
 internal static extern void z_axpy(IntPtr blasHandle, int n, Complex alpha, Complex[] x, [In, Out] Complex[] y);
        private void WaveIn_DataAvailable(object sender, WaveInEventArgs e)
        {
            byte[] buffer        = e.Buffer;
            int    bytesGrabados = e.BytesRecorded;

            int numMuestras = bytesGrabados / 2;

            int exponente  = 0;
            int numeroBits = 0;

            do
            {
                exponente++;
                numeroBits = (int)Math.Pow(2, exponente);
            } while (numeroBits < numMuestras);
            exponente -= 1;
            numeroBits = (int)Math.Pow(2, exponente);

            Complex[] muestrasComplejas = new Complex[numeroBits];

            for (int i = 0; i < bytesGrabados; i += 2)
            {
                short muestra       = (short)(buffer[i + 1] << 8 | buffer[i]);
                float muestra32bits = (float)muestra / 32768.0f;
                if (i / 2 < numeroBits)
                {
                    muestrasComplejas[i / 2].X = muestra32bits;
                }
            }
            FastFourierTransform.FFT(true, exponente, muestrasComplejas);
            float[] valoresAbsolutos = new float[muestrasComplejas.Length];

            for (int i = 0; i < muestrasComplejas.Length; i++)
            {
                valoresAbsolutos[i] = (float)Math.Sqrt(((muestrasComplejas[i].X * muestrasComplejas[i].X) + (muestrasComplejas[i].Y * muestrasComplejas[i].Y)));
            }
            int indiceValorMaximo = valoresAbsolutos.ToList().IndexOf(valoresAbsolutos.Max());

            float frecuenciaFundamental = (float)(indiceValorMaximo * formato.SampleRate) / (float)valoresAbsolutos.Length;

            lblFrecuencia.Text = frecuenciaFundamental.ToString("n") + " Hz";



            /* Aqui se modificann los valores para que hagan lo de apretar o aflojar la cuerda */
            //Inicio de la cuerda 6

            if (frecuenciaFundamental >= 149 && frecuenciaFundamental <= 159)   //esta floja
            {
                lblTono.Text = "Eb";
                imgFlechaDerecha.Visibility   = Visibility.Visible;
                imgFlechaIzquierda.Visibility = Visibility.Hidden;
                lblTono.Foreground            = Brushes.Gray;
            }
            else if (frecuenciaFundamental >= 169 && frecuenciaFundamental <= 179) //esta tensa
            {
                lblTono.Text = "E#";
                imgFlechaDerecha.Visibility   = Visibility.Hidden;
                imgFlechaIzquierda.Visibility = Visibility.Visible;
                lblTono.Foreground            = Brushes.Gray;
            }
            else if (frecuenciaFundamental >= 160 && frecuenciaFundamental <= 168) //esta al toque prro
            {
                imgFlechaDerecha.Visibility   = Visibility.Hidden;
                imgFlechaIzquierda.Visibility = Visibility.Hidden;
                lblTono.Text       = "E";
                lblTono.Foreground = Brushes.Green;
                lblCuerda.Text     = "Cuerda 6";
            }

            //Fin de la cuerda 6
            //comienzo de la cuerda 5

            else if (frecuenciaFundamental >= 204 && frecuenciaFundamental <= 214)   //esta floja
            {
                lblTono.Text = "Ab";
                imgFlechaDerecha.Visibility   = Visibility.Visible;
                imgFlechaIzquierda.Visibility = Visibility.Hidden;
                lblTono.Foreground            = Brushes.Gray;
            }
            else if (frecuenciaFundamental >= 226 && frecuenciaFundamental <= 236) //esta tensa
            {
                lblTono.Text = "A#";
                imgFlechaDerecha.Visibility   = Visibility.Hidden;
                imgFlechaIzquierda.Visibility = Visibility.Visible;
                lblTono.Foreground            = Brushes.Gray;
            }
            else if (frecuenciaFundamental >= 215 && frecuenciaFundamental <= 225) //esta al toque prro
            {
                imgFlechaDerecha.Visibility   = Visibility.Hidden;
                imgFlechaIzquierda.Visibility = Visibility.Hidden;
                lblTono.Text       = "A";
                lblTono.Foreground = Brushes.Green;
                lblCuerda.Text     = "Cuerda 5";
            }

            //fin de la cuerda 5
            //inicia la 4

            else if (frecuenciaFundamental >= 276 && frecuenciaFundamental <= 286)   //esta floja
            {
                lblTono.Text = "Db";
                imgFlechaDerecha.Visibility   = Visibility.Visible;
                imgFlechaIzquierda.Visibility = Visibility.Hidden;
                lblTono.Foreground            = Brushes.Gray;
            }
            else if (frecuenciaFundamental >= 298 && frecuenciaFundamental <= 308) //esta tensa
            {
                lblTono.Text = "D#";
                imgFlechaDerecha.Visibility   = Visibility.Hidden;
                imgFlechaIzquierda.Visibility = Visibility.Visible;
                lblTono.Foreground            = Brushes.Gray;
            }
            else if (frecuenciaFundamental >= 287 && frecuenciaFundamental <= 297) //esta al toque prro
            {
                imgFlechaDerecha.Visibility   = Visibility.Hidden;
                imgFlechaIzquierda.Visibility = Visibility.Hidden;
                lblTono.Text       = "D";
                lblTono.Foreground = Brushes.Green;
                lblCuerda.Text     = "Cuerda 4";
            }

            //termina la 4
            //inicia la 3

            else if (frecuenciaFundamental >= 180 && frecuenciaFundamental <= 190)   //esta floja
            {
                lblTono.Text = "Gb";
                imgFlechaDerecha.Visibility   = Visibility.Visible;
                imgFlechaIzquierda.Visibility = Visibility.Hidden;
                lblTono.Foreground            = Brushes.Gray;
            }
            else if (frecuenciaFundamental >= 198 && frecuenciaFundamental <= 203) //esta tensa
            {
                lblTono.Text = "G#";
                imgFlechaDerecha.Visibility   = Visibility.Hidden;
                imgFlechaIzquierda.Visibility = Visibility.Visible;
                lblTono.Foreground            = Brushes.Gray;
            }
            else if (frecuenciaFundamental >= 191 && frecuenciaFundamental <= 197) //esta al toque prro
            {
                imgFlechaDerecha.Visibility   = Visibility.Hidden;
                imgFlechaIzquierda.Visibility = Visibility.Hidden;
                lblTono.Text       = "G";
                lblTono.Foreground = Brushes.Green;
                lblCuerda.Text     = "Cuerda 3";
            }

            //termina la 3
            //inicia la 2

            else if (frecuenciaFundamental >= 237 && frecuenciaFundamental <= 242)   //esta floja
            {
                lblTono.Text = "Bb";
                imgFlechaDerecha.Visibility   = Visibility.Visible;
                imgFlechaIzquierda.Visibility = Visibility.Hidden;
                lblTono.Foreground            = Brushes.Gray;
            }
            else if (frecuenciaFundamental >= 250 && frecuenciaFundamental <= 260) //esta tensa
            {
                lblTono.Text = "B#";
                imgFlechaDerecha.Visibility   = Visibility.Hidden;
                imgFlechaIzquierda.Visibility = Visibility.Visible;
                lblTono.Foreground            = Brushes.Gray;
            }
            else if (frecuenciaFundamental >= 243 && frecuenciaFundamental <= 249) //esta al toque prro
            {
                imgFlechaDerecha.Visibility   = Visibility.Hidden;
                imgFlechaIzquierda.Visibility = Visibility.Hidden;
                lblTono.Text       = "B";
                lblTono.Foreground = Brushes.Green;
                lblCuerda.Text     = "Cuerda 2";
            }

            //termina la 2
            //comienza la 1

            else if (frecuenciaFundamental >= 313 && frecuenciaFundamental <= 323)   //esta floja
            {
                lblTono.Text = "eb";
                imgFlechaDerecha.Visibility   = Visibility.Visible;
                imgFlechaIzquierda.Visibility = Visibility.Hidden;
                lblTono.Foreground            = Brushes.Gray;
            }
            else if (frecuenciaFundamental >= 333 && frecuenciaFundamental <= 343) //esta tensa
            {
                lblTono.Text = "e#";
                imgFlechaDerecha.Visibility   = Visibility.Hidden;
                imgFlechaIzquierda.Visibility = Visibility.Visible;
                lblTono.Foreground            = Brushes.Gray;
            }
            else if (frecuenciaFundamental >= 324 && frecuenciaFundamental <= 332) //esta al toque prro
            {
                imgFlechaDerecha.Visibility   = Visibility.Hidden;
                imgFlechaIzquierda.Visibility = Visibility.Hidden;
                lblTono.Text       = "e";
                lblTono.Foreground = Brushes.Green;
                lblCuerda.Text     = "Cuerda 1";
            }

            /* Aquí termina el codigo de mostrar la nota */
        }
예제 #40
0
 internal static extern void z_scale(IntPtr blasHandle, int n, Complex alpha, [In, Out] Complex[] x);
예제 #41
0
        // Onset Detection function - Determines Start and Finish times of a note and the frequency of the note over each duration.

        private void onsetDetection()
        {
            float[] HFC;
            int     starts = 0;
            int     stops  = 0;

            List <int> lengths;
            List <int> noteStarts;
            List <int> noteStops;

            double  pi = 3.14159265;
            Complex i  = Complex.ImaginaryOne;

            double[] pitches = new double[100];

            noteStarts = new List <int>(100);
            noteStops  = new List <int>(100);
            lengths    = new List <int>(100);

            SolidColorBrush sheetBrush = new SolidColorBrush(Colors.Black);
            SolidColorBrush ErrorBrush = new SolidColorBrush(Colors.Red);
            SolidColorBrush whiteBrush = new SolidColorBrush(Colors.White);

            HFC = new float[stftRep.timeFreqData[0].Length];


            ////////////////////////////////////////////////////////////////////////
            ///                       Parallel Section                           ///
            ////////////////////////////////////////////////////////////////////////

            // Original and Chunked are slower

            //for (int jj = 0; jj < stftRep.timeFreqData[0].Length; jj++)
            //{
            //    for (int ii = 0; ii < stftRep.wSamp / 2; ii++)
            //    {
            //        HFC[jj] = HFC[jj] + (float)Math.Pow((double)stftRep.timeFreqData[ii][jj] * ii, 2);
            //    }
            //}

            int N = stftRep.timeFreqData[0].Length;

            Parallel.For(0, NUM_THREADS_USED, iterator =>
            {
                int chunk_size = (N + (NUM_THREADS_USED - 1)) / NUM_THREADS_USED;
                int start      = chunk_size * iterator;
                int end        = Math.Min(start + chunk_size, N);

                for (int jj = start; jj < end; jj++)
                {
                    for (int ii = 0; ii < stftRep.wSamp / 2; ii++)
                    {
                        HFC[jj] = HFC[jj] + (float)Math.Pow((double)stftRep.timeFreqData[ii][jj] * ii, 2);
                    }
                }
            });

            //Parallel.For(0, stftRep.timeFreqData[0].Length, jj =>
            //{
            //    for (int ii = 0; ii < stftRep.wSamp / 2; ii++)
            //    {
            //        HFC[jj] = HFC[jj] + (float)Math.Pow((double)stftRep.timeFreqData[ii][jj] * ii, 2);
            //    }
            //});

            ////////////////////////////// ~ END ~ /////////////////////////////////

            float maxi = HFC.Max();

            for (int jj = 0; jj < stftRep.timeFreqData[0].Length; jj++)
            {
                HFC[jj] = (float)Math.Pow((HFC[jj] / maxi), 2);
            }

            for (int jj = 0; jj < stftRep.timeFreqData[0].Length; jj++)
            {
                if (starts > stops)
                {
                    if (HFC[jj] < 0.001)
                    {
                        noteStops.Add(jj * ((stftRep.wSamp - 1) / 2));
                        stops = stops + 1;
                    }
                }
                else if (starts - stops == 0)
                {
                    if (HFC[jj] > 0.001)
                    {
                        noteStarts.Add(jj * ((stftRep.wSamp - 1) / 2));
                        starts = starts + 1;
                    }
                }
            }

            if (starts > stops)
            {
                noteStops.Add(waveIn.data.Length);
            }

            for (int ii = 0; ii < noteStops.Count; ii++)
            {
                lengths.Add(noteStops[ii] - noteStarts[ii]);
            }

            ////////////////////////////////////////////////////////////////////////
            ///                       Parallel Section                           ///
            ////////////////////////////////////////////////////////////////////////

            //Seq in other folder. Due to restructuring

            Parallel.For(0, NUM_THREADS_USED, iterator =>
            {
                int guardSize = lengths.Count;
                int chunkSize = (guardSize + (NUM_THREADS_USED - 1)) / NUM_THREADS_USED;
                int start     = chunkSize * iterator;
                int end       = Math.Min(start + chunkSize, guardSize);

                for (int mm = start; mm < end; mm++)
                {
                    Complex[] twiddles;
                    Complex[] compX;
                    Complex[] Y;
                    double[] absY;

                    int nearest = (int)Math.Pow(2, Math.Ceiling(Math.Log(lengths[mm], 2)));
                    twiddles    = new Complex[nearest];

                    for (int ll = 0; ll < nearest; ll++)
                    {
                        double a     = 2 * pi * ll / (double)nearest;
                        twiddles[ll] = Complex.Pow(Complex.Exp(-i), (float)a);
                    }

                    compX = new Complex[nearest];
                    for (int kk = 0; kk < nearest; kk++)
                    {
                        if (kk < lengths[mm] && (noteStarts[mm] + kk) < waveIn.wave.Length)
                        {
                            compX[kk] = waveIn.wave[noteStarts[mm] + kk];
                        }
                        else
                        {
                            compX[kk] = Complex.Zero;
                        }
                    }

                    Y = new Complex[nearest];

                    Y = fft(compX, nearest, twiddles);

                    double maximum = 0;
                    int maxInd     = 0;

                    absY = new double[nearest];

                    for (int jj = 0; jj < Y.Length; jj++)
                    {
                        absY[jj] = Y[jj].Magnitude;
                        if (absY[jj] > maximum)
                        {
                            maximum = absY[jj];
                            maxInd  = jj;
                        }
                    }

                    for (int div = 6; div > 1; div--)
                    {
                        if (maxInd > nearest / 2)
                        {
                            if (absY[(int)Math.Floor((double)(nearest - maxInd) / div)] / absY[(maxInd)] > 0.10)
                            {
                                maxInd = (nearest - maxInd) / div;
                            }
                        }
                        else
                        {
                            if (absY[(int)Math.Floor((double)maxInd / div)] / absY[(maxInd)] > 0.10)
                            {
                                maxInd = maxInd / div;
                            }
                        }
                    }

                    if (maxInd > nearest / 2)
                    {
                        pitches[mm] = (nearest - maxInd) * waveIn.SampleRate / nearest;
                    }
                    else
                    {
                        pitches[mm] = maxInd * waveIn.SampleRate / nearest;
                    }
                }
            });

            //Parallel.For(0, lengths.Count, mm =>
            //{
            //    Complex[] twiddles;
            //    Complex[] compX;
            //    Complex[] Y;
            //    double[] absY;

            //    int nearest = (int)Math.Pow(2, Math.Ceiling(Math.Log(lengths[mm], 2)));
            //    twiddles = new Complex[nearest];

            //    for (int ll = 0; ll < nearest; ll++)
            //    {
            //        double a = 2 * pi * ll / (double)nearest;
            //        twiddles[ll] = Complex.Pow(Complex.Exp(-i), (float)a);
            //    }

            //    compX = new Complex[nearest];
            //    for (int kk = 0; kk < nearest; kk++)
            //    {
            //        if (kk < lengths[mm] && (noteStarts[mm] + kk) < waveIn.wave.Length)
            //        {
            //            compX[kk] = waveIn.wave[noteStarts[mm] + kk];
            //        }
            //        else
            //        {
            //            compX[kk] = Complex.Zero;
            //        }
            //    }

            //    Y = new Complex[nearest];

            //    Y = fft(compX, nearest, twiddles);

            //    double maximum = 0;
            //    int maxInd = 0;

            //    absY = new double[nearest];

            //    for (int jj = 0; jj < Y.Length; jj++)
            //    {
            //        absY[jj] = Y[jj].Magnitude;
            //        if (absY[jj] > maximum)
            //        {
            //            maximum = absY[jj];
            //            maxInd = jj;
            //        }
            //    }

            //    for (int div = 6; div > 1; div--)
            //    {

            //        if (maxInd > nearest / 2)
            //        {
            //            if (absY[(int)Math.Floor((double)(nearest - maxInd) / div)] / absY[(maxInd)] > 0.10)
            //            {
            //                maxInd = (nearest - maxInd) / div;
            //            }
            //        }
            //        else
            //        {
            //            if (absY[(int)Math.Floor((double)maxInd / div)] / absY[(maxInd)] > 0.10)
            //            {
            //                maxInd = maxInd / div;
            //            }
            //        }
            //    }

            //    if (maxInd > nearest / 2)
            //    {
            //        pitches[mm] = (nearest - maxInd) * waveIn.SampleRate / nearest;
            //    }
            //    else
            //    {
            //        pitches[mm] = maxInd * waveIn.SampleRate / nearest;
            //    }
            //});

            ////////////////////////////// ~ END ~ /////////////////////////////////

            musicNote[] noteArray;
            noteArray = new musicNote[noteStarts.Count()];

            for (int ii = 0; ii < noteStarts.Count(); ii++)
            {
                noteArray[ii] = new musicNote(pitches[ii], lengths[ii]);
            }

            int[] sheetPitchArray = new int[sheetmusic.Length];
            int[] notePitchArray  = new int[noteArray.Length];

            for (int ii = 0; ii < sheetmusic.Length; ii++)
            {
                sheetPitchArray[ii] = sheetmusic[ii].pitch % 12;
            }

            for (int jj = 0; jj < noteArray.Length; jj++)
            {
                notePitchArray[jj] = noteArray[jj].pitch % 12;
            }

            string[] alignedStrings = new string[2];

            alignedStrings = stringMatch(sheetPitchArray, notePitchArray);

            musicNote[] alignedStaffArray = new musicNote[alignedStrings[0].Length / 2];
            musicNote[] alignedNoteArray  = new musicNote[alignedStrings[1].Length / 2];
            int         staffCount        = 0;
            int         noteCount         = 0;

            for (int ii = 0; ii < alignedStrings[0].Length / 2; ii++)
            {
                if (alignedStrings[0][2 * ii] == ' ')
                {
                    alignedStaffArray[ii] = new musicNote(0, 0);
                }
                else
                {
                    alignedStaffArray[ii] = sheetmusic[staffCount];
                    staffCount++;
                }

                if (alignedStrings[1][2 * ii] == ' ')
                {
                    alignedNoteArray[ii] = new musicNote(0, 0);
                }
                else
                {
                    alignedNoteArray[ii] = noteArray[noteCount];
                    noteCount++;
                }
            }

            // STAFF TAB DISPLAY -- Commented out to make timing consistant.

            //Ellipse[] notes;
            //Line[] stems;
            //notes = new Ellipse[alignedNoteArray.Length];
            //stems = new Line[alignedNoteArray.Length];
            //SolidColorBrush myBrush = new SolidColorBrush(Colors.Green);

            //RotateTransform rotate = new RotateTransform(45);

            //for (int ii = 0; ii < alignedNoteArray.Length; ii++)
            //{
            //    //noteArray[ii] = new musicNote(pitches[ii], lengths[ii]);
            //    //System.Console.Out.Write("Note " + (ii + 1) + ": \nDuration: " + noteArray[ii].duration / waveIn.SampleRate + " seconds \nPitch: " + Enum.GetName(typeof(musicNote.notePitch), (noteArray[ii].pitch) % 12) + " / " + pitches[ii] + "\nError: " + noteArray[ii].error * 100 + "%\n");
            //    notes[ii] = new Ellipse();
            //    notes[ii].Tag = alignedNoteArray[ii];
            //    notes[ii].Height = 20;
            //    notes[ii].Width = 15;
            //    notes[ii].Margin = new Thickness(ii * 30, 0, 0, 0);
            //    notes[ii].LayoutTransform = rotate;
            //    notes[ii].MouseEnter += DisplayStats;
            //    notes[ii].MouseLeave += ClearStats;
            //    stems[ii] = new Line();
            //    stems[ii].StrokeThickness = 1;
            //    stems[ii].X1 = ii * 30 + 20;
            //    stems[ii].X2 = ii * 30 + 20;
            //    stems[ii].Y1 = 250 - 10 * alignedNoteArray[ii].staffPos;
            //    stems[ii].Y2 = 250 - 10 * alignedNoteArray[ii].staffPos - 40;
            //    notes[ii].Fill = ErrorBrush;
            //    notes[ii].StrokeThickness = 1;
            //    stems[ii].Stroke = ErrorBrush;


            //    Canvas.SetTop(notes[ii], (240 - 10 * alignedNoteArray[ii].staffPos));
            //    if (alignedNoteArray[ii].flat)
            //    {
            //        System.Windows.Controls.Label flat = new System.Windows.Controls.Label();
            //        flat.Content = "b";
            //        flat.FontFamily = new FontFamily("Mistral");
            //        flat.Margin = new Thickness(ii * 30 + 15, 0, 0, 0);
            //        Canvas.SetTop(flat, (240 - 10 * alignedNoteArray[ii].staffPos));
            //        noteStaff.Children.Insert(ii, flat);
            //    }

            //    noteStaff.Children.Insert(ii, notes[ii]);
            //    noteStaff.Children.Insert(ii, stems[ii]);

            //}

            //Ellipse[] sheetNotes;
            //Rectangle[] timeRect;
            //Line[] sheetStems;
            //sheetNotes = new Ellipse[alignedStaffArray.Length];
            //sheetStems = new Line[alignedStaffArray.Length];
            //timeRect = new Rectangle[2 * alignedStaffArray.Length];

            //Fline.Width = alignedStaffArray.Length * 30;
            //Dline.Width = alignedStaffArray.Length * 30;
            //Bline.Width = alignedStaffArray.Length * 30;
            //Gline.Width = alignedStaffArray.Length * 30;
            //Eline.Width = alignedStaffArray.Length * 30;
            //noteStaff.Width = alignedStaffArray.Length * 30;


            //for (int ii = 0; ii < alignedStaffArray.Length; ii++)
            //{

            //    sheetNotes[ii] = new Ellipse();
            //    sheetNotes[ii].Tag = alignedStaffArray[ii];
            //    sheetNotes[ii].Height = 20;
            //    sheetNotes[ii].Width = 15;
            //    sheetNotes[ii].Margin = new Thickness(ii * 30, 0, 0, 0);
            //    sheetNotes[ii].LayoutTransform = rotate;
            //    sheetNotes[ii].MouseEnter += DisplayStats;
            //    sheetNotes[ii].MouseLeave += ClearStats;
            //    sheetStems[ii] = new Line();
            //    sheetStems[ii].StrokeThickness = 1;
            //    sheetStems[ii].X1 = ii * 30 + 20;
            //    sheetStems[ii].X2 = ii * 30 + 20;
            //    sheetStems[ii].Y1 = 250 - 10 * alignedStaffArray[ii].staffPos;
            //    sheetStems[ii].Y2 = 250 - 10 * alignedStaffArray[ii].staffPos - 40;

            //    sheetNotes[ii].Fill = sheetBrush;
            //    sheetNotes[ii].StrokeThickness = 1;
            //    sheetStems[ii].Stroke = sheetBrush;


            //    Canvas.SetTop(sheetNotes[ii], (240 - 10 * alignedStaffArray[ii].staffPos));
            //    if (alignedStaffArray[ii].flat)
            //    {
            //        System.Windows.Controls.Label flat = new System.Windows.Controls.Label();
            //        flat.Content = "b";
            //        flat.FontFamily = new FontFamily("Mistral");
            //        flat.Margin = new Thickness(ii * 30 + 15, 0, 0, 0);
            //        Canvas.SetTop(flat, (240 - 10 * alignedStaffArray[ii].staffPos));
            //        noteStaff.Children.Insert(ii, flat);
            //    }
            //    noteStaff.Children.Insert(ii, sheetNotes[ii]);
            //    noteStaff.Children.Insert(ii, sheetStems[ii]);
            //}

            //// FOR TIMING ERROR RECTANGLES

            //for (int ii = 0; ii < alignedStaffArray.Length; ii++)
            //{

            //    timeRect[ii] = new Rectangle();
            //    timeRect[ii].Fill = sheetBrush;
            //    timeRect[ii].Height = 10 * alignedStaffArray[ii].duration * 4 * bpm / (60 * waveIn.SampleRate);
            //    timeRect[ii].Width = 15;
            //    timeRect[ii].Margin = new Thickness(ii * 30 + 5, 0, 0, 0);

            //    Canvas.SetTop(timeRect[ii], 200);

            //    noteStaff.Children.Insert(ii, timeRect[ii]);

            //}

            //for (int ii = alignedStaffArray.Length; ii < alignedStaffArray.Length + alignedNoteArray.Length; ii++)
            //{

            //    timeRect[ii] = new Rectangle();
            //    timeRect[ii].Fill = ErrorBrush;
            //    timeRect[ii].Height = 10 * alignedNoteArray[ii - alignedStaffArray.Length].duration * 4 * bpm / (60 * waveIn.SampleRate);
            //    timeRect[ii].Width = 10;
            //    timeRect[ii].Margin = new Thickness((ii - alignedStaffArray.Length) * 30 + 5, 0, 0, 0);

            //    Canvas.SetTop(timeRect[ii], 200);
            //    noteStaff.Children.Insert(ii, timeRect[ii]);
            //}
        }
예제 #42
0
 internal static extern void z_matrix_multiply(IntPtr blasHandle, int transA, int transB, int m, int n, int k, Complex alpha, Complex[] x, Complex[] y, Complex beta, [In, Out] Complex[] c);
        /// <summary>
        /// Solves a system of linear equations, <b>Ax = b</b>, with A QR factorized.
        /// </summary>
        /// <param name="input">The right hand side vector, <b>b</b>.</param>
        /// <param name="result">The left hand side <see cref="Matrix{T}"/>, <b>x</b>.</param>
        public override void Solve(Vector <Complex> input, Vector <Complex> result)
        {
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }

            if (result == null)
            {
                throw new ArgumentNullException("result");
            }

            // Ax=b where A is an m x n matrix
            // Check that b is a column vector with m entries
            if (MatrixQ.RowCount != input.Count)
            {
                throw new ArgumentException(Resources.ArgumentVectorsSameLength);
            }

            // Check that x is a column vector with n entries
            if (MatrixQ.ColumnCount != result.Count)
            {
                throw Matrix.DimensionsDontMatch <ArgumentException>(MatrixQ, result);
            }

            var inputCopy = input.Clone();

            // Compute Y = transpose(Q)*B
            var column = new Complex[MatrixQ.RowCount];

            for (var k = 0; k < MatrixQ.RowCount; k++)
            {
                column[k] = inputCopy[k];
            }

            for (var i = 0; i < MatrixQ.ColumnCount; i++)
            {
                var s = Complex.Zero;
                for (var k = 0; k < MatrixQ.RowCount; k++)
                {
                    s += MatrixQ.At(k, i).Conjugate() * column[k];
                }

                inputCopy[i] = s;
            }

            // Solve R*X = Y;
            for (var k = MatrixQ.ColumnCount - 1; k >= 0; k--)
            {
                inputCopy[k] /= MatrixR.At(k, k);
                for (var i = 0; i < k; i++)
                {
                    inputCopy[i] -= inputCopy[k] * MatrixR.At(i, k);
                }
            }

            for (var i = 0; i < MatrixR.ColumnCount; i++)
            {
                result[i] = inputCopy[i];
            }
        }
예제 #44
0
        internal override void InitVelocityConstraints(ref SolverData data)
        {
            _indexA       = BodyA.IslandIndex;
            _indexB       = BodyB.IslandIndex;
            _localCenterA = BodyA._sweep.LocalCenter;
            _localCenterB = BodyB._sweep.LocalCenter;
            _invMassA     = BodyA._invMass;
            _invMassB     = BodyB._invMass;
            _invIA        = BodyA._invI;
            _invIB        = BodyB._invI;

            Vector2 cA = data.positions[_indexA].c;
            float   aA = data.positions[_indexA].a;
            Vector2 vA = data.velocities[_indexA].v;
            float   wA = data.velocities[_indexA].w;

            Vector2 cB = data.positions[_indexB].c;
            float   aB = data.positions[_indexB].a;
            Vector2 vB = data.velocities[_indexB].v;
            float   wB = data.velocities[_indexB].w;

            Complex qA = Complex.FromAngle(aA);
            Complex qB = Complex.FromAngle(aB);

            _rA = Complex.Multiply(LocalAnchorA - _localCenterA, ref qA);
            _rB = Complex.Multiply(LocalAnchorB - _localCenterB, ref qB);
            _u  = cB + _rB - cA - _rA;

            // Handle singularity.
            float length = _u.Length();

            if (length > Settings.LinearSlop)
            {
                _u *= 1.0f / length;
            }
            else
            {
                _u = Vector2.Zero;
            }

            float crAu    = MathUtils.Cross(ref _rA, ref _u);
            float crBu    = MathUtils.Cross(ref _rB, ref _u);
            float invMass = _invMassA + _invIA * crAu * crAu + _invMassB + _invIB * crBu * crBu;

            // Compute the effective mass matrix.
            _mass = invMass != 0.0f ? 1.0f / invMass : 0.0f;

            if (Frequency > 0.0f)
            {
                float C = length - Length;

                // Frequency
                float omega = 2.0f * MathHelper.Pi * Frequency;

                // Damping coefficient
                float d = 2.0f * _mass * DampingRatio * omega;

                // Spring stiffness
                float k = _mass * omega * omega;

                // magic formulas
                float h = data.step.dt;
                _gamma = h * (d + h * k);
                _gamma = _gamma != 0.0f ? 1.0f / _gamma : 0.0f;
                _bias  = C * h * k * _gamma;

                invMass += _gamma;
                _mass    = invMass != 0.0f ? 1.0f / invMass : 0.0f;
            }
            else
            {
                _gamma = 0.0f;
                _bias  = 0.0f;
            }

            if (data.step.warmStarting)
            {
                // Scale the impulse to support a variable time step.
                _impulse *= data.step.dtRatio;

                Vector2 P = _impulse * _u;
                vA -= _invMassA * P;
                wA -= _invIA * MathUtils.Cross(ref _rA, ref P);
                vB += _invMassB * P;
                wB += _invIB * MathUtils.Cross(ref _rB, ref P);
            }
            else
            {
                _impulse = 0.0f;
            }

            data.velocities[_indexA].v = vA;
            data.velocities[_indexA].w = wA;
            data.velocities[_indexB].v = vB;
            data.velocities[_indexB].w = wB;
        }
 // this is to allow saving of large arrays separately as a binary file
 public BinaryArraySerializer[] GetBinarySerializers()
 {
     return(new[]
     {
         new BinaryArraySerializer
         {
             DataArray = Mean,
             Name = "Mean",
             FileTag = "",
             WriteData = binaryWriter =>
             {
                 for (int i = 0; i < Fx.Count; i++)
                 {
                     for (int j = 0; j < MTBins.Count - 1; j++)
                     {
                         binaryWriter.Write(Mean[i, j].Real);
                         binaryWriter.Write(Mean[i, j].Imaginary);
                     }
                 }
             },
             ReadData = binaryReader =>
             {
                 Mean = Mean ?? new Complex[Fx.Count, MTBins.Count - 1];
                 for (int i = 0; i < Fx.Count; i++)
                 {
                     for (int j = 0; j < MTBins.Count - 1; j++)
                     {
                         var real = binaryReader.ReadDouble();
                         var imag = binaryReader.ReadDouble();
                         Mean[i, j] = new Complex(real, imag);
                     }
                 }
             }
         },
         new BinaryArraySerializer
         {
             DataArray = FractionalMT,
             Name = "FractionalMT",
             FileTag = "_FractionalMT",
             WriteData = binaryWriter =>
             {
                 for (int i = 0; i < Fx.Count; i++)
                 {
                     for (int k = 0; k < MTBins.Count - 1; k++)
                     {
                         for (int m = 0; m < FractionalMTBins.Count + 1; m++)
                         {
                             binaryWriter.Write(FractionalMT[i, k, m].Real);
                             binaryWriter.Write(FractionalMT[i, k, m].Imaginary);
                         }
                     }
                 }
             },
             ReadData = binaryReader =>
             {
                 FractionalMT = FractionalMT ??
                                new Complex[Fx.Count, MTBins.Count - 1, FractionalMTBins.Count + 1];
                 for (int i = 0; i < Fx.Count; i++)
                 {
                     for (int k = 0; k < MTBins.Count - 1; k++)
                     {
                         for (int m = 0; m < FractionalMTBins.Count + 1; m++)
                         {
                             var real = binaryReader.ReadDouble();
                             var imag = binaryReader.ReadDouble();
                             FractionalMT[i, k, m] = new Complex(real, imag);
                         }
                     }
                 }
             }
         },
         new BinaryArraySerializer
         {
             DataArray = TotalMTOfZ,
             Name = "TotalMTOfZ",
             FileTag = "_TotalMTOfZ",
             WriteData = binaryWriter =>
             {
                 for (int i = 0; i < Fx.Count; i++)
                 {
                     for (int l = 0; l < Z.Count - 1; l++)
                     {
                         binaryWriter.Write(TotalMTOfZ[i, l].Real);
                         binaryWriter.Write(TotalMTOfZ[i, l].Imaginary);
                     }
                 }
             },
             ReadData = binaryReader =>
             {
                 TotalMTOfZ = TotalMTOfZ ?? new Complex[Fx.Count, Z.Count - 1];
                 for (int i = 0; i < Fx.Count; i++)
                 {
                     for (int l = 0; l < Z.Count - 1; l++)
                     {
                         var real = binaryReader.ReadDouble();
                         var imag = binaryReader.ReadDouble();
                         TotalMTOfZ[i, l] = new Complex(real, imag);
                     }
                 }
             }
         },
         new BinaryArraySerializer
         {
             DataArray = DynamicMTOfZ,
             Name = "DynamicMTOfZ",
             FileTag = "_DynamicMTOfZ",
             WriteData = binaryWriter =>
             {
                 for (int i = 0; i < Fx.Count; i++)
                 {
                     for (int l = 0; l < Z.Count - 1; l++)
                     {
                         binaryWriter.Write(DynamicMTOfZ[i, l].Real);
                         binaryWriter.Write(DynamicMTOfZ[i, l].Imaginary);
                     }
                 }
             },
             ReadData = binaryReader =>
             {
                 DynamicMTOfZ = DynamicMTOfZ ?? new Complex[Fx.Count, Z.Count - 1];
                 for (int i = 0; i < Fx.Count; i++)
                 {
                     for (int l = 0; l < Z.Count - 1; l++)
                     {
                         var real = binaryReader.ReadDouble();
                         var imag = binaryReader.ReadDouble();
                         DynamicMTOfZ[i, l] = new Complex(real, imag);
                     }
                 }
             }
         },
         new BinaryArraySerializer
         {
             DataArray = SubregionCollisions,
             Name = "SubregionCollisions",
             FileTag = "_SubregionCollisions",
             WriteData = binaryWriter =>
             {
                 for (int i = 0; i < NumSubregions; i++)
                 {
                     for (int l = 0; l < 2; l++)
                     {
                         binaryWriter.Write(SubregionCollisions[i, l]);
                     }
                 }
             },
             ReadData = binaryReader =>
             {
                 SubregionCollisions = SubregionCollisions ??
                                       new double[NumSubregions, 2];
                 for (int i = 0; i < NumSubregions; i++)
                 {
                     for (int l = 0; l < 2; l++)
                     {
                         SubregionCollisions[i, l] = binaryReader.ReadDouble();
                     }
                 }
             }
         },
         // return a null serializer, if we're not serializing the second moment
         !TallySecondMoment
             ? null
             : new BinaryArraySerializer
         {
             DataArray = TotalMTOfZSecondMoment,
             Name = "TotalMTOfZSecondMoment",
             FileTag = "_TotalMTOfZ_2",
             WriteData = binaryWriter =>
             {
                 if (!TallySecondMoment || TotalMTOfZSecondMoment == null)
                 {
                     return;
                 }
                 for (int i = 0; i < Fx.Count; i++)
                 {
                     for (int j = 0; j < Z.Count - 1; j++)
                     {
                         binaryWriter.Write(TotalMTOfZSecondMoment[i, j].Real);
                         binaryWriter.Write(TotalMTOfZSecondMoment[i, j].Imaginary);
                     }
                 }
             },
             ReadData = binaryReader =>
             {
                 if (!TallySecondMoment || TotalMTOfZSecondMoment == null)
                 {
                     return;
                 }
                 TotalMTOfZSecondMoment = new Complex[Fx.Count, Z.Count - 1];
                 for (int i = 0; i < Fx.Count; i++)
                 {
                     for (int j = 0; j < Z.Count - 1; j++)
                     {
                         var real = binaryReader.ReadDouble();
                         var imag = binaryReader.ReadDouble();
                         TotalMTOfZSecondMoment[i, j] = new Complex(real, imag);
                     }
                 }
             },
         },
         new BinaryArraySerializer
         {
             DataArray = DynamicMTOfZSecondMoment,
             Name = "DynamicMTOfZSecondMoment",
             FileTag = "_DynamicMTOfZ_2",
             WriteData = binaryWriter =>
             {
                 if (!TallySecondMoment || DynamicMTOfZSecondMoment == null)
                 {
                     return;
                 }
                 for (int i = 0; i < Fx.Count; i++)
                 {
                     for (int j = 0; j < Z.Count - 1; j++)
                     {
                         binaryWriter.Write(DynamicMTOfZSecondMoment[i, j].Real);
                         binaryWriter.Write(DynamicMTOfZSecondMoment[i, j].Imaginary);
                     }
                 }
             },
             ReadData = binaryReader =>
             {
                 if (!TallySecondMoment || DynamicMTOfZSecondMoment == null)
                 {
                     return;
                 }
                 DynamicMTOfZSecondMoment = new Complex[Fx.Count, Z.Count - 1];
                 for (int i = 0; i < Fx.Count; i++)
                 {
                     for (int j = 0; j < Z.Count - 1; j++)
                     {
                         var real = binaryReader.ReadDouble();
                         var imag = binaryReader.ReadDouble();
                         DynamicMTOfZSecondMoment[i, j] = new Complex(real, imag);
                     }
                 }
             },
         },
         new BinaryArraySerializer
         {
             DataArray = SecondMoment,
             Name = "SecondMoment",
             FileTag = "_2",
             WriteData = binaryWriter =>
             {
                 if (!TallySecondMoment || SecondMoment == null)
                 {
                     return;
                 }
                 for (int i = 0; i < Fx.Count; i++)
                 {
                     for (int j = 0; j < MTBins.Count - 1; j++)
                     {
                         binaryWriter.Write(SecondMoment[i, j].Real);
                         binaryWriter.Write(SecondMoment[i, j].Imaginary);
                     }
                 }
             },
             ReadData = binaryReader =>
             {
                 if (!TallySecondMoment || SecondMoment == null)
                 {
                     return;
                 }
                 SecondMoment = new Complex[Fx.Count, MTBins.Count - 1];
                 for (int i = 0; i < Fx.Count - 1; i++)
                 {
                     for (int j = 0; j < MTBins.Count - 1; j++)
                     {
                         var real = binaryReader.ReadDouble();
                         var imag = binaryReader.ReadDouble();
                         SecondMoment[i, j] = new Complex(real, imag);
                     }
                 }
             },
         },
     });
 }
        public override void MatrixMultiplyWithUpdate(Transpose transposeA, Transpose transposeB, Complex alpha, Complex[] a, int rowsA, int columnsA, Complex[] b, int rowsB, int columnsB, Complex beta, Complex[] c)
        {
            if (a == null)
            {
                throw new ArgumentNullException(nameof(a));
            }

            if (b == null)
            {
                throw new ArgumentNullException(nameof(b));
            }

            if (c == null)
            {
                throw new ArgumentNullException(nameof(c));
            }

            var m = transposeA == Transpose.DontTranspose ? rowsA : columnsA;
            var n = transposeB == Transpose.DontTranspose ? columnsB : rowsB;
            var k = transposeA == Transpose.DontTranspose ? columnsA : rowsA;
            var l = transposeB == Transpose.DontTranspose ? rowsB : columnsB;

            if (c.Length != m * n)
            {
                throw new ArgumentException(Resources.ArgumentMatrixDimensions);
            }

            if (k != l)
            {
                throw new ArgumentException(Resources.ArgumentMatrixDimensions);
            }

            SafeNativeMethods.z_matrix_multiply(transposeA, transposeB, m, n, k, alpha, a, b, beta, c);
        }
예제 #47
0
        private void btnDoOneMeasurement_Click(object sender, EventArgs e)
        {
            Complex imp = Program.a.GetMeasurement();

            this.label148.Text = AgilentHelper.ImpedanceToString(imp, false);
        }
        /// <summary>
        /// Solves a system of linear equations, <b>AX = B</b>, with A QR factorized.
        /// </summary>
        /// <param name="input">The right hand side <see cref="Matrix{T}"/>, <b>B</b>.</param>
        /// <param name="result">The left hand side <see cref="Matrix{T}"/>, <b>X</b>.</param>
        public override void Solve(Matrix <Complex> input, Matrix <Complex> result)
        {
            // Check for proper arguments.
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }

            if (result == null)
            {
                throw new ArgumentNullException("result");
            }

            // The solution X should have the same number of columns as B
            if (input.ColumnCount != result.ColumnCount)
            {
                throw new ArgumentException(Resources.ArgumentMatrixSameColumnDimension);
            }

            // The dimension compatibility conditions for X = A\B require the two matrices A and B to have the same number of rows
            if (MatrixQ.RowCount != input.RowCount)
            {
                throw new ArgumentException(Resources.ArgumentMatrixSameRowDimension);
            }

            // The solution X row dimension is equal to the column dimension of A
            if (MatrixQ.ColumnCount != result.RowCount)
            {
                throw new ArgumentException(Resources.ArgumentMatrixSameColumnDimension);
            }

            var inputCopy = input.Clone();

            // Compute Y = transpose(Q)*B
            var column = new Complex[MatrixQ.RowCount];

            for (var j = 0; j < input.ColumnCount; j++)
            {
                for (var k = 0; k < MatrixQ.RowCount; k++)
                {
                    column[k] = inputCopy.At(k, j);
                }

                for (var i = 0; i < MatrixQ.ColumnCount; i++)
                {
                    var s = Complex.Zero;
                    for (var k = 0; k < MatrixQ.RowCount; k++)
                    {
                        s += MatrixQ.At(k, i).Conjugate() * column[k];
                    }

                    inputCopy.At(i, j, s);
                }
            }

            // Solve R*X = Y;
            for (var k = MatrixQ.ColumnCount - 1; k >= 0; k--)
            {
                for (var j = 0; j < input.ColumnCount; j++)
                {
                    inputCopy.At(k, j, inputCopy.At(k, j) / MatrixR.At(k, k));
                }

                for (var i = 0; i < k; i++)
                {
                    for (var j = 0; j < input.ColumnCount; j++)
                    {
                        inputCopy.At(i, j, inputCopy.At(i, j) - (inputCopy.At(k, j) * MatrixR.At(i, k)));
                    }
                }
            }

            for (var i = 0; i < MatrixR.ColumnCount; i++)
            {
                for (var j = 0; j < input.ColumnCount; j++)
                {
                    result.At(i, j, inputCopy.At(i, j));
                }
            }
        }
예제 #49
0
 public static Complex Round(Complex value) => new Complex(Math.Round(value.Real), Math.Round(value.Imaginary));
        /// <summary>
        /// method to tally to detector
        /// </summary>
        /// <param name="photon">photon data needed to tally</param>
        public void Tally(Photon photon)
        {
            if (!IsWithinDetectorAperture(photon))
            {
                return;
            }

            // calculate the radial bin to attribute the deposition
            var    tissueMT  = new double[2]; // 2 is for [static, dynamic] tally separation
            bool   talliedMT = false;
            double totalMT   = 0;
            var    totalMTOfZForOnePhoton   = new Complex[Fx.Count, Z.Count - 1];
            var    dynamicMTOfZForOnePhoton = new Complex[Fx.Count, Z.Count - 1];
            var    fxArray            = Fx.AsEnumerable().ToArray();
            var    x                  = photon.DP.Position.X; // use final exiting x position
            var    sinNegativeTwoPiFX = fxArray.Select(fx => Math.Sin(-2 * Math.PI * fx * x)).ToArray();
            var    cosNegativeTwoPiFX = fxArray.Select(fx => Math.Cos(-2 * Math.PI * fx * x)).ToArray();

            // go through photon history and claculate momentum transfer
            // assumes that no MT tallied at pseudo-collisions (reflections and refractions)
            // this algorithm needs to look ahead to angle of next DP, but needs info from previous to determine whether real or pseudo-collision
            PhotonDataPoint previousDP = photon.History.HistoryData.First();
            PhotonDataPoint currentDP  = photon.History.HistoryData.Skip(1).Take(1).First();

            foreach (PhotonDataPoint nextDP in photon.History.HistoryData.Skip(2))
            {
                if (previousDP.Weight != currentDP.Weight)                // only for true collision points
                {
                    var csr = _tissue.GetRegionIndex(currentDP.Position); // get current region index
                    // get z bin of current position
                    var iz = DetectorBinning.WhichBin(currentDP.Position.Z, Z.Count - 1, Z.Delta, Z.Start);
                    // get angle between current and next
                    double cosineBetweenTrajectories = Direction.GetDotProduct(currentDP.Direction, nextDP.Direction);
                    var    momentumTransfer          = 1 - cosineBetweenTrajectories;
                    totalMT += momentumTransfer;
                    for (int ifx = 0; ifx < Fx.Count; ifx++)
                    {
                        var deltaWeight = photon.DP.Weight * cosNegativeTwoPiFX[ifx] +
                                          Complex.ImaginaryOne * sinNegativeTwoPiFX[ifx];
                        TotalMTOfZ[ifx, iz]             += deltaWeight * momentumTransfer;
                        totalMTOfZForOnePhoton[ifx, iz] += deltaWeight * momentumTransfer;
                    }

                    if (_rng.NextDouble() < _bloodVolumeFraction[csr]) // hit blood
                    {
                        tissueMT[1] += momentumTransfer;
                        for (int ifx = 0; ifx < Fx.Count; ifx++)
                        {
                            var deltaWeight = photon.DP.Weight * cosNegativeTwoPiFX[ifx] +
                                              Complex.ImaginaryOne * sinNegativeTwoPiFX[ifx];
                            DynamicMTOfZ[ifx, iz]             += deltaWeight * momentumTransfer;
                            dynamicMTOfZForOnePhoton[ifx, iz] += deltaWeight * momentumTransfer;
                        }

                        SubregionCollisions[csr, 1] += 1; // add to dynamic collision count
                    }
                    else // index 0 captures static events
                    {
                        tissueMT[0] += momentumTransfer;
                        SubregionCollisions[csr, 0] += 1; // add to static collision count
                    }

                    talliedMT = true;
                }

                previousDP = currentDP;
                currentDP  = nextDP;
            }

            if (totalMT > 0.0) // only tally if momentum transfer accumulated
            {
                var imt = DetectorBinning.WhichBin(totalMT, MTBins.Count - 1, MTBins.Delta, MTBins.Start);
                for (int ifx = 0; ifx < Fx.Count; ifx++)
                {
                    var deltaWeight = photon.DP.Weight * cosNegativeTwoPiFX[ifx] +
                                      Complex.ImaginaryOne * sinNegativeTwoPiFX[ifx];
                    Mean[ifx, imt] += deltaWeight;
                    if (TallySecondMoment)
                    {
                        SecondMoment[ifx, imt] += deltaWeight * deltaWeight;
                        for (int i = 0; i < Fx.Count - 1; i++)
                        {
                            for (int j = 0; j < Z.Count - 1; j++)
                            {
                                TotalMTOfZSecondMoment[i, j] +=
                                    totalMTOfZForOnePhoton[i, j] * totalMTOfZForOnePhoton[i, j];
                                DynamicMTOfZSecondMoment[i, j] +=
                                    dynamicMTOfZForOnePhoton[i, j] * dynamicMTOfZForOnePhoton[i, j];
                            }
                        }
                    }

                    if (talliedMT)
                    {
                        TallyCount++;
                    }

                    // tally DYNAMIC fractional MT in each subregion
                    int ifrac;
                    for (int isr = 0; isr < NumSubregions; isr++)
                    {
                        // add 1 to ifrac to offset bin 0 added for =0 only tallies
                        ifrac = DetectorBinning.WhichBin(tissueMT[1] / totalMT,
                                                         FractionalMTBins.Count - 1, FractionalMTBins.Delta, FractionalMTBins.Start) + 1;
                        // put identically 0 fractional MT into separate bin at index 0
                        if (tissueMT[1] / totalMT == 0.0)
                        {
                            ifrac = 0;
                        }

                        // put identically 1 fractional MT into separate bin at index Count+1 -1
                        if (tissueMT[1] / totalMT == 1.0)
                        {
                            ifrac = FractionalMTBins.Count;
                        }

                        FractionalMT[ifx, imt, ifrac] += deltaWeight;
                    }
                }
            }
        }
예제 #51
0
 public static Complex Ceiling(Complex value) => new Complex(Math.Ceiling(value.Real), Math.Ceiling(value.Imaginary));
예제 #52
0
        public static Complex Sign(Complex value)
        {
            var arg = Math.Atan2(value.Imaginary, value.Real);

            return(new Complex(Math.Cos(arg), Math.Sin(arg)));
        }
예제 #53
0
 public static Complex Min(Complex a, Complex b) => IsGreaterThan(a, b) ? b : a;
예제 #54
0
 public static Complex Floor(Complex value) => new Complex(Math.Floor(value.Real), Math.Floor(value.Imaginary));
예제 #55
0
 public static Boolean IsGreaterThan(Complex a, Complex b) => Complex.Abs(a) > Complex.Abs(b);
예제 #56
0
 public static Complex Max(Complex a, Complex b) => IsGreaterThan(a, b) ? a : b;
예제 #57
0
 public static Complex Acsch(Complex value) => Complex.Log(1.0 / value + Complex.Sqrt(1.0 / (value * value) + 1.0));
예제 #58
0
 public static Boolean IsLessThan(Complex a, Complex b) => Complex.Abs(a) < Complex.Abs(b);
예제 #59
0
 public static Complex Csch(Complex value) => 2.0 / (Complex.Exp(value) - Complex.Exp(-value));
예제 #60
0
 public static Complex Log2(Complex value) => Complex.Log(value, 2.0);