Ejemplo n.º 1
1
 public static void HwAcceleratedSumInPlace(int[] lhs, int[] rhs)
 {
     var simdLength = Vector<int>.Count;
     var i = 0;
     for (i = 0; i < lhs.Length - simdLength; i += simdLength) {
         var va = new Vector<int>(lhs, i);
         var vb = new Vector<int>(rhs, i);
         va += vb;
         va.CopyTo(lhs, i);
     }
     for (; i < lhs.Length; ++i) {
         lhs[i] += rhs[i];
     }
 }
Ejemplo n.º 2
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DenseVector"/> class by
 /// copying the values from another.
 /// </summary>
 /// <param name="other">
 /// The vector to create the new vector from.
 /// </param>
 public DenseVector(Vector<Complex> other) : this(other.Count)
 {
         CommonParallel.For(
             0, 
             Data.Length, 
             index => this[index] = other[index]);
 }
Ejemplo n.º 3
0
        public Ray4( Ray[] rays )
        {
            int l = rays.Length;
        
            float[] ox4 = new float[l], oy4 = new float[l], oz4 = new float[l];
            float[] dx4 = new float[l], dy4 = new float[l], dz4 = new float[l];
            float[] t = new float[l];
            float[] nx4 = new float[l], ny4 = new float[l], nz4 = new float[l];
            int[] objIdx = new int[l];
            int[] inside = new int[l];
        
            for (int i = 0; i < rays.Length; i++)
            {
                ox4[i] = rays[i].O.X; oy4[i] = rays[i].O.Y; oz4[i] = rays[i].O.Z;
                dx4[i] = rays[i].D.X; dy4[i] = rays[i].D.Y; dz4[i] = rays[i].D.Z;
                t[i] = rays[i].t;
                nx4[i] = rays[i].N.X; ny4[i] = rays[i].N.Y; nz4[i] = rays[i].N.Z;
                objIdx[i] = rays[i].objIdx;
                inside[i] = rays[i].inside ? 1 : 0;
            }

            Ox4 = new Vector<float>(ox4); Oy4 = new Vector<float>(oy4); Oz4 = new Vector<float>(oz4);
            Dx4 = new Vector<float>(dx4); Dy4 = new Vector<float>(dy4); Dz4 = new Vector<float>(dz4);
            t4 = new Vector<float>(t);
            Nx4 = new Vector<float>(nx4); Ny4 = new Vector<float>(ny4); Nz4 = new Vector<float>(nz4);
            objIdx4 = new Vector<int>(objIdx);
            inside4 = new Vector<int>(inside);
            returnMask = new Vector<int>(0);
        }
Ejemplo n.º 4
0
        public static bool ContainsPossibly(byte[] buffer, int index, int end, ref Vector<byte> value)
        {
            if (!Vector.IsHardwareAccelerated || index + Vector<byte>.Count >= end || index + Vector<byte>.Count >= buffer.Length)
                return true;

            return !Vector.Equals(new Vector<byte>(buffer, index), value).Equals(Vector<byte>.Zero);
        }
Ejemplo n.º 5
0
 static int Main(string[] args)
 {
     {
         var a = new Vector<uint>(1000000);
         var b = new Vector<uint>(0);
         var c = new Vector<uint>(1);
         var d = b - c;
         var e = d / a;
         if (e[0] != 4294)
         {
             return 0;
         }
     }
     {
         var a = new Vector<int>(1000000);
         var b = new Vector<int>(0);
         var c = new Vector<int>(1);
         var d = b - c;
         var e = d / a;
         if (e[0] != 0)
         {
             return 0;
         }
     }
     return 100;
 }
        public VectorizedSceneUpdateNodesTests()
        {
            Width = 20;
            Height = 20;
            Length = 1f;

            Grid = new PackedHexagonalGrid(Width, Height, Padding, Length);
            NodesX = Grid.VerticesX.ToArray();
            NodesY = Grid.VerticesY.ToArray();

            var random = new Random();
            Func<float> randomFloat = () => (float)random.NextDouble();

            VelocitiesX = Enumerable.Range(0, NodesX.Length).Select(_ => randomFloat()).ToArray();
            VelocitiesY = Enumerable.Range(0, NodesY.Length).Select(_ => randomFloat()).ToArray();

            const float dt = 0.01f;
            Dt = new Vector<float>(dt);

            UpdateNodesReferenceImplementation(dt, NodesX, NodesY, VelocitiesX, VelocitiesY);
            ReferenceNodesX = NodesX.ToArray();
            ReferenceNodesY = NodesY.ToArray();

            RestoreNodes();

            JitMethods();
        }
Ejemplo n.º 7
0
 internal static void HWAcceleratedGetStats(ushort[] input, out ushort min, out ushort max, out double average)
 {
     var simdLength = Vector<ushort>.Count;
     var vmin = new Vector<ushort>(ushort.MaxValue);
     var vmax = new Vector<ushort>(ushort.MinValue);
     var i = 0;
     ulong total = 0;
     var lastSafeVectorIndex = input.Length - simdLength;
     for (i = 0; i < lastSafeVectorIndex; i += simdLength) {
         total += input[i];
         total += input[i + 1];
         total += input[i + 2];
         total += input[i + 3];
         total += input[i + 4];
         total += input[i + 5];
         total += input[i + 6];
         total += input[i + 7];
         var vector = new Vector<ushort>(input, i);
         vmin = Vector.Min(vector, vmin);
         vmax = Vector.Max(vector, vmax);
     }
     min = ushort.MaxValue;
     max = ushort.MinValue;
     for (var j = 0; j < simdLength; ++j) {
         min = Math.Min(min, vmin[j]);
         max = Math.Max(max, vmax[j]);
     }
     for (; i < input.Length; ++i) {
         min = Math.Min(min, input[i]);
         max = Math.Max(max, input[i]);
         total += input[i];
     }
     average = total / (double)input.Length;
 }
Ejemplo n.º 8
0
	public Plane( Vector3 ABC, float D )
	{
		Nx = new Vector<float>(ABC.X);
        Ny = new Vector<float>(ABC.Y);
        Nz = new Vector<float>(ABC.Z);
        d = new Vector<float>(D);
	}
Ejemplo n.º 9
0
	public Plane( float A, float B, float C, float D )
    {
        Nx = new Vector<float>(A);
        Ny = new Vector<float>(B);
        Nz = new Vector<float>(C);
        d = new Vector<float>(D);
    }
Ejemplo n.º 10
0
        /// <summary>
        /// Approximates the solution to the matrix equation <b>Ax = b</b>.
        /// </summary>
        /// <param name="rhs">The right hand side vector.</param>
        /// <param name="lhs">The left hand side vector. Also known as the result vector.</param>
        public void Approximate(Vector rhs, Vector lhs)
        {
            if (rhs == null)
            {
                throw new ArgumentNullException("rhs");
            }

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

            if (_inverseDiagonals == null)
            {
                throw new ArgumentException(Resources.ArgumentMatrixDoesNotExist);
            }

            if ((lhs.Count != rhs.Count) || (lhs.Count != _inverseDiagonals.Length))
            {
                throw new ArgumentException(Resources.ArgumentVectorsSameLength, "rhs");
            }

            for (var i = 0; i < _inverseDiagonals.Length; i++)
            {
                lhs[i] = rhs[i] * _inverseDiagonals[i];
            }
        }
Ejemplo n.º 11
0
            public Vector<double> lms(Vector<double> signal, Vector<double> filtered_signal, int window_size)
            {
                int signal_size = signal.Count;

                double mi = 0.07; //Współczynnik szybkości adaptacji

                Vector<double> coeff = Vector<double>.Build.Dense(window_size, 0); //Wektor z wagami filtru
                Vector<double> bufor = Vector<double>.Build.Dense(window_size, 0); //Inicjalizacja bufora sygnału wejściowego
                Vector<double> out_signal = Vector<double>.Build.Dense(signal_size, 0);

                double dest;
                double err;

                for(int i = 0; i<signal_size; i++)
                {

                    bufor.CopySubVectorTo(bufor, 0, 1, window_size - 1);
                    bufor[0] = signal[i];

                    dest = coeff * bufor;
                    err = filtered_signal[i] - dest;

                    coeff.Add(2 * mi * err * bufor,coeff);

                    //coeff = coeff + (2 * mi * err * bufor);

                    out_signal[i] = dest;

                }

                return out_signal;
            }
Ejemplo n.º 12
0
        public static double[] Multiply_SIMD_2(Matrix A, Matrix B)
        {
            // Abour 50% fateser when matrix size >= 8x8

            var vecSize = Vector<double>.Count;
            var bRemainer = B.Columns % Vector<double>.Count;
            if (B.Columns % Vector<double>.Count != 0)
            {
                B.AddColumns(bRemainer);
            }

            var C = new double[A.Rows * B.Columns];

            for (int i = 0; i < A.Rows; i++)
            {
                for (int k = 0; k < A.Columns; k++)
                {
                    for (int j = 0; j < B.Columns; j += vecSize)
                    {
                        var vC = new Vector<double>(C, i * A.Rows + j);
                        var vB = new Vector<double>(B.internalArray, k * B.Columns + j);
                        var vA = new Vector<double>(A.internalArray[i * A.Columns + k]);
                        vC += vA * vB;
                        vC.CopyTo(C, i * A.Rows + j);
                    }
                }
            }

            return C.ToArray();
        }
        public void SeekWorksAcrossBlocks()
        {
            Console.WriteLine($"Vector.IsHardwareAccelerated == {Vector.IsHardwareAccelerated}");
            Console.WriteLine($"Vector<byte>.Count == {Vector<byte>.Count}");

            using (var pool = new MemoryPool2())
            {
                var block1 = pool.Lease(256);
                var block2 = block1.Next = pool.Lease(256);
                var block3 = block2.Next = pool.Lease(256);

                foreach (var ch in Enumerable.Range(0, 34).Select(x => (byte)x))
                {
                    block1.Array[block1.End++] = ch;
                }
                foreach (var ch in Enumerable.Range(34, 25).Select(x => (byte)x))
                {
                    block2.Array[block2.End++] = ch;
                }
                foreach (var ch in Enumerable.Range(59, 197).Select(x => (byte)x))
                {
                    block3.Array[block3.End++] = ch;
                }

                var vectorMaxValues = new Vector<byte>(byte.MaxValue);

                var iterator = block1.GetIterator();
                foreach (var ch in Enumerable.Range(0, 256).Select(x => (byte)x))
                {
                    var vectorCh = new Vector<byte>(ch);

                    var hit = iterator;
                    hit.Seek(ref vectorCh);
                    Assert.Equal(ch, iterator.GetLength(hit));

                    hit = iterator;
                    hit.Seek(ref vectorCh, ref vectorMaxValues);
                    Assert.Equal(ch, iterator.GetLength(hit));

                    hit = iterator;
                    hit.Seek(ref vectorMaxValues, ref vectorCh);
                    Assert.Equal(ch, iterator.GetLength(hit));

                    hit = iterator;
                    hit.Seek(ref vectorCh, ref vectorMaxValues, ref vectorMaxValues);
                    Assert.Equal(ch, iterator.GetLength(hit));

                    hit = iterator;
                    hit.Seek(ref vectorMaxValues, ref vectorCh, ref vectorMaxValues);
                    Assert.Equal(ch, iterator.GetLength(hit));

                    hit = iterator;
                    hit.Seek(ref vectorMaxValues, ref vectorMaxValues, ref vectorCh);
                    Assert.Equal(ch, iterator.GetLength(hit));
                }
            }
        }
Ejemplo n.º 14
0
        public static string ConvertToString(BigInteger n, bool escape, int radix)
        {
            if (radix == -1)
            {
                radix = (int)Runtime.GetDynamic(Symbols.PrintBase);
            }

            if (radix == -1)
            {
                radix = 10;
            }
            else if (radix < 2 || radix > 36)
            {
                throw new LispException("Invalid number base: {0}", radix);
            }

            if (n == 0)
            {
                return "0";
            }

            var sign = (n >= 0) ? "" : "-";
            n = (n >= 0) ? n : -n;
            var stk = new Vector();
            while (n != 0)
            {
                var d = (int)(n % radix);
                if (d <= 9)
                {
                    stk.Add((char)(d + '0'));
                }
                else {
                    stk.Add((char)(d - 10 + 'a'));
                }
                n = n / radix;
            }
            stk.Reverse();
            if (escape)
            {
                switch (radix)
                {
                    case 10:
                        return sign + Runtime.MakeString(stk.ToArray());
                    case 16:
                        return sign + "0x" + Runtime.MakeString(stk.ToArray());
                    case 8:
                        return sign + "0" + Runtime.MakeString(stk.ToArray());
                    case 2:
                        return "#b" + sign + Runtime.MakeString(stk.ToArray());
                    default:
                        return "#" + radix + "r" + sign + Runtime.MakeString(stk.ToArray());
                }
            }
            else {
                return sign + Runtime.MakeString(stk.ToArray());
            }
        }
Ejemplo n.º 15
0
 public unsafe BoundingBoxWide(BoundingBox* boundingBoxes, Vector<int>[] masks)
 {
     Min = new Vector3Wide(ref boundingBoxes[0].Min);
     Max = new Vector3Wide(ref boundingBoxes[0].Max);
     for (int i = 1; i < Vector<float>.Count; ++i)
     {
         BoundingBoxWide wide = new BoundingBoxWide(ref boundingBoxes[i]);
         ConditionalSelect(ref masks[i], ref wide, ref this, out this);
     }
 }
Ejemplo n.º 16
0
 private static void SumVector(float[] a, float[] b, float[] c)
 {
     int N = c.Length;
     for (int i = 0; i < N; i += Vector<Single>.Count) // Count returns 16 for char, 4 for float, 2 for double.
     {
         var aSimd = new Vector<Single>(a, i); // create instance with offset i
         var bSimd = new Vector<Single>(b, i);
         Vector<Single> cSimd = aSimd + bSimd; // or Vector<Single> c_simd = Vector.Add(b_simd, a_simd);
         cSimd.CopyTo(c, i); //copy to array with offset
     }
 }
        protected override void CheckResult(IPreConditioner<Complex> preconditioner, SparseMatrix matrix, Vector<Complex> vector, Vector<Complex> result)
        {
            Assert.AreEqual(typeof(UnitPreconditioner), preconditioner.GetType(), "#01");

            // Unit preconditioner is doing nothing. Vector and result should be equal

            for (var i = 0; i < vector.Count; i++)
            {
                Assert.IsTrue(vector[i] == result[i], "#02-" + i);
            }
        }
Ejemplo n.º 18
0
 static public Vector<float> Cosine4(Vector<float> alpha)
 {
     Vector<float> result = Vector<float>.One, lastTerm = Vector<float>.One;
     Vector<float> alpha2 = alpha * alpha;
     for (int i = 1; i < TERMS; i++)
     {
         lastTerm = Vector.Negate(lastTerm * alpha2);
         result += lastTerm / factorials[i * 2];
     }
     return result;
 }
Ejemplo n.º 19
0
        public static unsafe bool ContainsPossibly(byte[] buffer, int index, int end, ref Vector<short> value)
        {
            if (!Vector.IsHardwareAccelerated || index + Vector<byte>.Count + 1 >= end || index + Vector<byte>.Count + 1 >= buffer.Length)
                return true;

            fixed (byte* bufferPtr = buffer)
            {
                return
                !Vector.Equals(Unsafe.Read<Vector<short>>(bufferPtr + index), value).Equals(Vector<short>.Zero) ||
                !Vector.Equals(Unsafe.Read<Vector<short>>(bufferPtr + index + 1), value).Equals(Vector<short>.Zero);
            }
        }
Ejemplo n.º 20
0
 public BandGetImpulseTests()
 {
     int n = 20 * 20 * 3; // Must be a multiple of VectorizedScene.VectorSize (a multiple of 16 should be safe).
     NodesX1 = RandomFloats(n);
     NodesY1 = RandomFloats(n);
     NodesX2 = RandomFloats(n);
     NodesY2 = RandomFloats(n);
     RestLength = new Vector<float>(0.01f);
     Lambda = new Vector<float>(2);
     ImpulsesX = new float[n];
     ImpulsesY = new float[n];
 }
Ejemplo n.º 21
0
 public static void HwAcceleratedSumUnchecked(ushort[] lhs, ushort[] rhs, ushort[] result)
 {
     var simdLength = Vector<ushort>.Count;
     var i = 0;
     for (i = 0; i < lhs.Length - simdLength; i += simdLength) {
         var va = new Vector<ushort>(lhs, i);
         var vb = new Vector<ushort>(rhs, i);
         (va + vb).CopyTo(result, i);
     }
     for (; i < lhs.Length; ++i) {
         result[i] = (ushort)(lhs[i] + rhs[i]);
     }
 }
Ejemplo n.º 22
0
 public static void HwAcceleratedSumInPlace(float[] lhs, float[] rhs)
 {
     int simdLength = Vector<float>.Count;
     int i = 0;
     for (i = 0; i < lhs.Length - simdLength; i += simdLength) {
         Vector<float> va = new Vector<float>(lhs, i);
         Vector<float> vb = new Vector<float>(rhs, i);
         va += vb;
         va.CopyTo(lhs, i);
     }
     for (; i < lhs.Length; ++i) {
         lhs[i] += rhs[i];
     }
 }
Ejemplo n.º 23
0
 static int Foo(Vector<int> vec)
 {
     int[] a = new int[5];
     // The index [5] is outside the bounds of array 'a',
     // so this should throw ArgumentOutOfRangeException.
     // There's a subsequent check for whether the destination
     // has enough space to receive the vector, which would
     // raise an ArgumentException; the bug was that assertion
     // prop was using the later exception check to prove the
     // prior one "redundant" because the commas confused the
     // ordering.
     vec.CopyTo(a, 5);
     return a[0];
 }
        /// <summary>
        /// Sorts the elements of the <paramref name="values"/> vector in decreasing
        /// fashion using heap sort algorithm. The vector itself is not affected.
        /// </summary>
        /// <param name="lowerBound">The starting index.</param>
        /// <param name="upperBound">The stopping index.</param>
        /// <param name="sortedIndices">An array that will contain the sorted indices once the algorithm finishes.</param>
        /// <param name="values">The <see cref="Vector{T}"/> that contains the values that need to be sorted.</param>
        private static void HeapSortDoublesIndices(int lowerBound, int upperBound, int[] sortedIndices, Vector<Complex> values)
        {
            var start = ((upperBound - lowerBound + 1) / 2) - 1 + lowerBound;
            var end = (upperBound - lowerBound + 1) - 1 + lowerBound;

            BuildDoubleIndexHeap(start, upperBound - lowerBound + 1, sortedIndices, values);

            while (end >= lowerBound)
            {
                Exchange(sortedIndices, end, lowerBound);
                SiftDoubleIndices(sortedIndices, values, lowerBound, end);
                end -= 1;
            }
        }
Ejemplo n.º 25
0
        protected override void CheckResult(IPreConditioner<Complex> preconditioner, SparseMatrix matrix, Vector<Complex> vector, Vector<Complex> result)
        {
            Assert.AreEqual(typeof(Diagonal), preconditioner.GetType(), "#01");

            // Compute M * result = product
            // compare vector and product. Should be equal
            Vector<Complex> product = new DenseVector(result.Count);
            matrix.Multiply(result, product);

            for (var i = 0; i < product.Count; i++)
            {
                Assert.IsTrue(vector[i].Real.AlmostEqual(product[i].Real, -Epsilon.Magnitude()), "#02-" + i);
                Assert.IsTrue(vector[i].Imaginary.AlmostEqual(product[i].Imaginary, -Epsilon.Magnitude()), "#03-" + i);
            }
        }
Ejemplo n.º 26
0
        public static void HwAcceleratedSum(float[] lhs, float[] rhs, float[] result)
        {
            var simdLength = Vector<float>.Count;
            int i;
            for (i = 0; i < lhs.Length - simdLength; i += simdLength) {
                var va = new Vector<float>(lhs, i);
                var vb = new Vector<float>(rhs, i);
                va += vb;
                va.CopyTo(result, i);
            }

            for (; i < lhs.Length; ++i) {
                result[i] = lhs[i] + rhs[i];
            }
        }
Ejemplo n.º 27
0
 static public void DiffuseReflection4(Random rng, Ray4 ray, ref Vector<float> Rx4, ref Vector<float> Ry4, ref Vector<float> Rz4)
 {
     Vector<float> r1 = RandomFloat4(rng);
     Vector<float> r2 = RandomFloat4(rng);
     Vector<float> r = Vector.SquareRoot(Vector<float>.One - r1 * r1);
     Vector<float> phi = 2 * new Vector<float>(PI) * r2;
     Rx4 = Cosine4(phi) * r;
     Ry4 = Sine4(phi) * r;
     Rz4 = r1;
     Vector<float> NdotR = ray.Nx4 * Rx4 + ray.Ny4 * Ry4 + ray.Nz4 * Rz4;
     Vector<int> mask = Vector.LessThan(NdotR, Vector<float>.Zero);
     Rx4 = Vector.ConditionalSelect(mask, Vector.Negate(Rx4), Rx4);
     Ry4 = Vector.ConditionalSelect(mask, Vector.Negate(Ry4), Ry4);
     Rz4 = Vector.ConditionalSelect(mask, Vector.Negate(Rz4), Rz4);
 }
Ejemplo n.º 28
0
        private void randomTest_button_Click(object sender, RoutedEventArgs e)
        {
            Vector <short> blah = new Vector <short>(short.MaxValue);
            int            calc = Vector <short> .Count * short.MaxValue;
            int            sum1 = Vector.Dot <short>(blah, Vector <short> .One);

            Vector <int> widenTarget1, widenTarget2;

            Vector.Widen(blah, out widenTarget1, out widenTarget2);
            int sum2 = Vector.Dot <int>(widenTarget1, Vector <int> .One) + Vector.Dot <int>(widenTarget2, Vector <int> .One);

            MessageBox.Show("Calculated: " + calc + ", summed (short): " + sum1 + ", summed (Widen,int):" + sum2);

            // Test performance
            long result1 = 0, result2 = 0;
            int  vectorLength = Vector <short> .Count;

            long time1 = 0, time2 = 0;
            long lastTime = 0;

            var watch = System.Diagnostics.Stopwatch.StartNew();

            // Do this 100 times
            for (int v = 0; v < 100; v++)
            {
                // Do 1 million of each
                for (int i = 0; i < 1000000; i++)
                {
                    Vector.Widen(blah, out widenTarget1, out widenTarget2);
                    result1 += Vector.Dot <int>(widenTarget1, Vector <int> .One) + Vector.Dot <int>(widenTarget2, Vector <int> .One);
                }
                time1   += watch.ElapsedMilliseconds - lastTime;
                lastTime = watch.ElapsedMilliseconds;


                for (int i = 0; i < 1000000; i++)
                {
                    for (int a = 0; a < vectorLength; a++)
                    {
                        result2 += blah[a];
                    }
                }
                time2   += watch.ElapsedMilliseconds - lastTime;
                lastTime = watch.ElapsedMilliseconds;
            }

            MessageBox.Show("100 million operations in milliseconds: Time (widen & dot): " + time1 + ", Time (iterate via for): " + time2);
        }
Ejemplo n.º 29
0
            public Vector<double> butterworth(Vector<double> signal, double fs, double fc, int order, Filtr_Type type)
            {
                //TODO: Comments

                int L = signal.Count;
                int DCGain = 1;

                double[] DoubleArray = new double[L];
                DoubleArray = signal.ToArray();

                Complex[] ComplexArray = new Complex[L];

                for (int i = 0; i < L; i++)
                {
                    ComplexArray[i] = new Complex(DoubleArray[i], 0);
                }

                Fourier.Forward(ComplexArray, FourierOptions.Matlab);

                double binWidth, binFreq, gain;

                if (fc > 0)
                {
                    binWidth = fs / L;

                    for(int i = 0; i < (L/2); i++)
                    {
                        binFreq = binWidth * (i+1);
                        gain = DCGain / Math.Sqrt(1 + Math.Pow(binFreq/fc, 2.0 * order));
                        if (type == Filtr_Type.HIGHPASS)
                        {
                            gain = 1 - gain;
                        }
                        ComplexArray[i] *= gain;
                        ComplexArray[L - 1 - i] *= gain;
                    }
                }

                Fourier.Inverse(ComplexArray, FourierOptions.Matlab);

                for (int i = 0; i < L; i++)
                {
                    DoubleArray[i] = ComplexArray[i].Real;
                }

                Vector<double> output_signal = Vector<double>.Build.DenseOfArray(DoubleArray);
                return output_signal;
            }
Ejemplo n.º 30
0
        public static int[] HWAcceleratedSumFunc(int[] lhs, int[] rhs)
        {
            var simdLength = Vector<int>.Count;
            var result = new int[lhs.Length];
            var i = 0;
            for (i = 0; i < lhs.Length - simdLength; i += simdLength) {
                var va = new Vector<int>(lhs, i);
                var vb = new Vector<int>(rhs, i);
                (va + vb).CopyTo(result, i);
            }
            for (; i < lhs.Length; ++i) {
                result[i] = lhs[i] + rhs[i];
            }

            return result;
        }
Ejemplo n.º 31
0
        public static void GetImpulse(Vector<float> nodeX1, Vector<float> nodeY1,
            Vector<float> nodeX2, Vector<float> nodeY2, Vector<float> restLength, Vector<float> lambda,
            out Vector<float> impulseX, out Vector<float> impulseY)
        {
            var rX = nodeX1 - nodeX2;
            var rY = nodeY1 - nodeY2;

            var length = Vector.SquareRoot(rX * rX + rY * rY);

            var displacement = length - restLength;
            var impulse = lambda * displacement;

            var factor = impulse / length;
            impulseX = rX * factor;
            impulseY = rY * factor;
        }
Ejemplo n.º 32
0
        private async Task processVideo()
        {
            //int maxThreads =

            var progressHandler = new Progress <ProcessingProgressReport>(value =>
            {
                status_txt.Text = value.message;
                if (value.drawStats)
                {
                    drawStats(value.currentIndex);
                }
            });
            var progress = progressHandler as IProgress <ProcessingProgressReport>;
            await Task.Run(() =>
            {
                int frameCount           = loadedVideo.Length;
                int[] sortedIndizi       = new int[loadedVideo.Length];
                bool[] alreadyUsedFrames = new bool[loadedVideo.Length];
                alreadyUsedFrames[0]     = true;

                int width             = loadedVideo[0].width;
                int height            = loadedVideo[0].height;
                int pixelCount        = width *height;
                int pixelCountX3      = width *height * 3;
                int stride            = loadedVideo[0].stride;
                int channelMultiplier = 3;


                // Stats
                Stopwatch stopWatch = new Stopwatch();
                ProcessingProgressReport progressReport = new ProcessingProgressReport();
                fps = new float[loadedVideo.Length];
                smallestDifferences        = new float[loadedVideo.Length];
                lowestFPS                  = float.PositiveInfinity;
                highestFPS                 = 0;
                smallestSmallestDifference = float.PositiveInfinity;
                highestSmallestDifference  = 0;

                // Vectorization related stuff
                int elementsPerVector       = Vector <short> .Count;
                int elementsPerTwoVectors   = 2 * elementsPerVector;
                int maxDifferencesPerVector = short.MaxValue / 255; // How often can we add a difference (assuming unlikely case of 255 each time) to a vector until it overflows? Then we need to flush.
                int oneFrameTotalLength     = loadedVideo[0].imageData.Length;

                if (loadedVideo[0].pixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb)
                {
                    channelMultiplier = 4;
                }

                Console.WriteLine(loadedVideo[0].pixelFormat);

                int currentFrame = 0;
                //Vector3Image currentFrameData;

                double[] frameDifferences = new double[frameCount];

                int maxWorkers = 0;
                int maxCompletionPortThreads = 0;
                ThreadPool.GetMaxThreads(out maxWorkers, out maxCompletionPortThreads);


                progress.Report("Starting processing of " + frameCount + " frames with up to " + maxWorkers + "(workers)/" + maxCompletionPortThreads + "(IO) ...");
#if DEBUG
                try
                {
#endif

                stopWatch.Start();
                for (int currentIndex = 0; currentIndex < frameCount; currentIndex++)
                {// not to confuse with current frame. We're just tracking our progress here.
                    double smallestDifference   = double.PositiveInfinity;
                    int smallestDifferenceFrame = -1;

                    //currentFrameData = new Vector3Image(loadedVideo[currentFrame]);
                    //ParallelOptions options = new ParallelOptions();
                    //options.MaxDegreeOfParallelism = 4;

                    double smallestDifferenceImpreciseOpt = double.PositiveInfinity;
                    // Go through all frames, comparing them to the current frame
                    Parallel.For(0, frameCount, (compareFrame) =>
                    {
                        //File.WriteAllText(compareFrame + ".txt", ""); // debug


                        frameDifferences[compareFrame] = double.PositiveInfinity;
                        if (compareFrame == currentFrame)
                        {
                            return;                               // No need to compare to itself.
                        }
                        if (alreadyUsedFrames[compareFrame] == true)
                        {
                            return;                                          // No need to go through already used frames
                        }
                        double thisFrameDifference = 0;

                        /*Vector3 thisFrameRGBDifference = new Vector3() { X = 0, Y = 0, Z = 0 };
                         * Vector3 currentFramePixel = new Vector3() { X = 0, Y = 0, Z = 0 };
                         * Vector3 compareFramePixel = new Vector3() { X = 0, Y = 0, Z = 0 };*/
                        Vector <short> thisFrameRGBDifference = new Vector <short>(0);
                        Vector <short> currentFramePixel      = new Vector <short>();
                        Vector <short> currentFramePixel2     = new Vector <short>();
                        Vector <short> compareFramePixel      = new Vector <short>();
                        Vector <short> compareFramePixel2     = new Vector <short>();

                        //Vector<short> tmpDiff = new Vector<short>();


                        // Calculate difference
                        int baseIndex;
                        //int pixelOffsetBase;

                        int i, a;
                        int donePixelsPerVectorElement = 0;
                        for (i = 0; i < oneFrameTotalLength; i += elementsPerTwoVectors)
                        {
                            Vector.Widen(new Vector <sbyte>(loadedVideo[currentFrame].imageData, i), out currentFramePixel, out currentFramePixel2);
                            Vector.Widen(new Vector <sbyte>(loadedVideo[compareFrame].imageData, i), out compareFramePixel, out compareFramePixel2);
                            thisFrameRGBDifference += Vector.Abs <short>(currentFramePixel - compareFramePixel);
                            thisFrameRGBDifference += Vector.Abs <short>(currentFramePixel2 - compareFramePixel2);

                            // Danger: XOR fuckery
                            //tmpDiff = currentFramePixel - compareFramePixel;
                            //(tmpDiff ^ (tmpDiff >> 31)) - (tmpDiff >> 31);
                            // /Danger XOR fuckery over


                            donePixelsPerVectorElement += 2;

                            if (donePixelsPerVectorElement >= (maxDifferencesPerVector - 2))
                            {
                                for (a = 0; a < elementsPerVector; a++)
                                {
                                    thisFrameDifference += thisFrameRGBDifference[a];
                                }
                                donePixelsPerVectorElement = 0;
                                if (thisFrameDifference / pixelCountX3 > smallestDifferenceImpreciseOpt)
                                {
                                    break;
                                }
                                thisFrameRGBDifference = new Vector <short>(0);
                            }

                            /*for(a=0; a < elementsPerVector; a++)
                             * {
                             *  currentFramePixel.Item[]
                             * }*/
                        }
                        if (donePixelsPerVectorElement > 0)
                        {
                            for (a = 0; a < elementsPerVector; a++)
                            {
                                thisFrameDifference += thisFrameRGBDifference[a];
                            }
                        }

                        /*
                         * for (int y = 0; y < height; y++)
                         * {
                         *  //pixelOffsetBase = y * width;
                         *  for (int x = 0; x < width; x++)
                         *  {
                         *      baseIndex = stride * y + x * channelMultiplier;
                         *      currentFramePixel.X = loadedVideo[currentFrame].imageData[baseIndex];
                         *      currentFramePixel.Y = loadedVideo[currentFrame].imageData[baseIndex + 1];
                         *      currentFramePixel.Z = loadedVideo[currentFrame].imageData[baseIndex + 2];
                         *      compareFramePixel.X = loadedVideo[compareFrame].imageData[baseIndex];
                         *      compareFramePixel.Y = loadedVideo[compareFrame].imageData[baseIndex + 1];
                         *      compareFramePixel.Z = loadedVideo[compareFrame].imageData[baseIndex + 2];
                         *      thisFrameRGBDifference += Vector3.Abs(currentFramePixel - compareFramePixel);
                         *      //thisFrameRGBDifference += Vector3.Abs(currentFrameData.imageData[pixelOffsetBase+x]-compareFramePixel);
                         *      //thisFrameDifference += Math.Abs(loadedVideo[currentFrame].imageData[baseIndex] - loadedVideo[compareFrame].imageData[baseIndex]);
                         *      //thisFrameDifference += Math.Abs(loadedVideo[currentFrame].imageData[baseIndex + 1] - loadedVideo[compareFrame].imageData[baseIndex + 1]);
                         *      //thisFrameDifference += Math.Abs(loadedVideo[currentFrame].imageData[baseIndex + 2] - loadedVideo[compareFrame].imageData[baseIndex + 2]);
                         *  }
                         *  //if (thisFrameDifference / pixelCountX3 > smallestDifferenceImpreciseOpt) break; // fast skip for very different frames. Since this is multithreaded, this might not always be correct in the sense of always having the right number in smallestDifference, but might work as optimization.
                         *  thisFrameDifference = thisFrameRGBDifference.X + thisFrameRGBDifference.Y + thisFrameRGBDifference.Z;
                         *  if (thisFrameDifference / pixelCountX3 > smallestDifferenceImpreciseOpt) break; // fast skip for very different frames. Since this is multithreaded, this might not always be correct in the sense of always having the right number in smallestDifference, but might work as optimization.
                         * }
                         * thisFrameDifference = thisFrameRGBDifference.X + thisFrameRGBDifference.Y + thisFrameRGBDifference.Z;*/
                        frameDifferences[compareFrame] = thisFrameDifference / pixelCountX3;
                        if (frameDifferences[compareFrame] < smallestDifferenceImpreciseOpt)
                        {
                            smallestDifferenceImpreciseOpt = frameDifferences[compareFrame];
                        }

                        //if (compareFrame % 1000 == 0)
                        //{
                        //    progress.Report("Processing: " + currentIndex + "/" + frameCount + " ordered frames. Current frame is "+currentFrame+" comparing to "+compareFrame);
                        //}
                    });



                    for (int compareFrame = 0; compareFrame < frameCount; compareFrame++)
                    {
                        if (frameDifferences[compareFrame] < smallestDifference)
                        {
                            smallestDifference      = frameDifferences[compareFrame];
                            smallestDifferenceFrame = compareFrame;
                        }
                    }


                    /*for (int compareFrame = 0; compareFrame < frameCount; compareFrame++)
                     * {
                     *  frameDifferences[compareFrame] = double.PositiveInfinity;
                     *  if (compareFrame == currentFrame) continue; // No need to compare to itself.
                     *  if (alreadyUsedFrames[compareFrame] == true) continue; // No need to go through already used frames
                     *
                     *  double thisFrameDifference = 0;
                     *  // Calculate difference
                     *  int baseIndex;
                     *  for (int y = 0; y < height; y++)
                     *  {
                     *      for (int x = 0; x < width; x++)
                     *      {
                     *          baseIndex = stride * y + x*channelMultiplier;
                     *          thisFrameDifference += Math.Abs(loadedVideo[currentFrame].imageData[baseIndex] - loadedVideo[compareFrame].imageData[baseIndex]);
                     *          thisFrameDifference += Math.Abs(loadedVideo[currentFrame].imageData[baseIndex + 1] - loadedVideo[compareFrame].imageData[baseIndex + 1]);
                     *          thisFrameDifference += Math.Abs(loadedVideo[currentFrame].imageData[baseIndex + 2] - loadedVideo[compareFrame].imageData[baseIndex + 2]);
                     *      }
                     *      if (thisFrameDifference / pixelCountX3 > smallestDifferenceImpreciseOpt) break; // fast skip for very different frames. Since this is multithreaded, this might not always be correct in the sense of always having the right number in smallestDifference, but might work as optimization.
                     *  }
                     *  frameDifferences[compareFrame] = thisFrameDifference / pixelCountX3;
                     *  if (frameDifferences[compareFrame] < smallestDifference)
                     *  {
                     *      smallestDifference = frameDifferences[compareFrame];
                     *      smallestDifferenceFrame = compareFrame;
                     *  }
                     * }*/


                    //Stats
                    fps[currentIndex] = 1 / ((float)stopWatch.ElapsedTicks / (float)Stopwatch.Frequency);
                    if (fps[currentIndex] < lowestFPS)
                    {
                        lowestFPS = fps[currentIndex];
                    }
                    if (fps[currentIndex] > highestFPS)
                    {
                        highestFPS = fps[currentIndex];
                    }
                    smallestDifferences[currentIndex] = (float)smallestDifference;
                    if (smallestDifference < smallestSmallestDifference)
                    {
                        smallestSmallestDifference = smallestDifferences[currentIndex];
                    }
                    if (smallestDifference > highestSmallestDifference && smallestDifference != double.PositiveInfinity)
                    {
                        highestSmallestDifference = smallestDifferences[currentIndex];
                    }
                    progressReport.drawStats = currentIndex % 100 == 0; // Only after 100 processed frames draw stats, to not have a notable performance impact
                    stopWatch.Restart();

                    // Status update
                    progressReport.message      = "Processing: " + currentIndex + "/" + frameCount + " ordered frames. Current frame is " + currentFrame + ", last smallest difference was " + smallestDifference;
                    progressReport.currentIndex = currentIndex;
                    progress.Report(progressReport);

                    if (smallestDifferenceFrame != -1)
                    {
                        sortedIndizi[currentIndex] = smallestDifferenceFrame;
                        currentFrame = smallestDifferenceFrame;
                        alreadyUsedFrames[smallestDifferenceFrame] = true;
                    }
                }
#if DEBUG
            }
                           catch (Exception e)
            {
                MessageBox.Show("le error: " + e.Message);
            }
#endif
                progressReport.message      = "Processing finished";
                progressReport.drawStats    = true;
                progressReport.currentIndex = frameCount - 1;
                progress.Report(progressReport);
                orderedVideo = sortedIndizi;
            });

            status_txt.Text                      = "Completed processing.";
            videoIsLoaded                        = true;
            loadVideo_button.IsEnabled           = true;
            processVideo_button.IsEnabled        = true;
            saveSortedFrameList_button.IsEnabled = true;
            saveSortedVideo_button.IsEnabled     = true;
        }
Ejemplo n.º 33
0
 static App()
 {
     dummy = Vector <float> .One;
 }