public void Axpy(double alpha, ArraySlice<double> x, ArraySlice<double> y)
        {
            if (x.Length != y.Length)
                throw new ArgumentException(Constants.Exceptions.ArrayLengthMustBeEqual);

            VclNativeMethods.vclAxpy(x.Length, alpha, x.Array, x.Offset, y.Array, y.Offset);
        }
        public void Divide(ArraySlice<double> a, ArraySlice<double> b)
        {
            if (a.Length != b.Length)
                throw new ArgumentException(Constants.Exceptions.ArrayLengthMustBeEqual);

            VclNativeMethods.vclDivide(a.Length, a.Array, a.Offset, b.Array, b.Offset);
        }
        public double Dot(ArraySlice<double> x, int incx, ArraySlice<double> y, int incy)
        {
            if (incx <= 0 || incy <= 0)
                throw new ArgumentException(Constants.Exceptions.IncrementsMustBePositive);

            return VclNativeMethods.vclDotEx(x.Length, x.Array, x.Offset, incx, y.Array, y.Offset, incy);
        }
        public double Dot(ArraySlice<double> x, ArraySlice<double> y)
        {
            if (x.Length != y.Length)
                throw new ArgumentException(Constants.Exceptions.ArrayLengthMustBeEqual);

            return VclNativeMethods.vclDot(x.Length, x.Array, x.Offset, y.Array, y.Offset);
        }
Example #5
0
        protected internal static void Fidct(float[,] bloque, float[,] bloqueDct, int tamX, int tamY)
        {
            var bloqueS = new ArraySlice<float>(bloque);

            // Sacamos el IDCT de cada fila del bloque
            for (int y = 0; y < tamY; y++)
            {
                Ifct8(bloqueS.GetSlice(y), coefYUS.GetSlice(y), tCosXU);
            }

            Common.Transpose(coefYU, coefUY, tamX, tamY);

            // Ahora sacamos el DCT por columna de los resultados anteriores
            for (int u = 0; u < tamX; u++)
            {
                Ifct8(coefUYS.GetSlice(u), coefUVS.GetSlice(u), tCosYV);
            }

            for (int v = 0; v < tamY; v++)
            {
                for (int u = 0; u < tamX; u++)
                {
                    bloqueDct[v, u] = (float)Math.Round(coefUV[u, v]);
                }
            }
        }
Example #6
0
 internal static void VerifyCopyTo <T>(ArraySlice <T> slice, T[] copyToTargetArray) where T : unmanaged, IEquatable <T>
 {
     slice.CopyTo(copyToTargetArray, 1);
     for (int i = 0; i < slice.Count; ++i)
     {
         Assert.Equal(slice[i], copyToTargetArray[i + 1]);
     }
 }
        void ICpuTensorMath.Scale(double alpha, ArraySlice <double> x)
        {
            Contract.Requires(x != null);
            Contract.Requires(!double.IsNaN(alpha));
            Contract.Requires(Contract.ForAll(x, xx => !double.IsNaN(xx)));

            Contract.Ensures(Contract.ForAll(x, xx => !double.IsNaN(xx)));
        }
Example #8
0
 public static NDArray array <T>(T[,,,] data) where T : unmanaged
 {
     if (data == null)
     {
         throw new ArgumentNullException(nameof(data));
     }
     return(new NDArray(ArraySlice.FromArray(data.Cast <T>().ToArray()), new Shape(data.GetLength(0), data.GetLength(1), data.GetLength(2), data.GetLength(3))));
 }
Example #9
0
 int AutoResizeAndGetChars(ArraySlice <byte> buf, ref char[] outChars, int outIndex, int neededOutSize, bool flush)
 {
     if (outChars.Length < neededOutSize)
     {
         Array.Resize(ref outChars, neededOutSize);
     }
     return(_decoder.GetChars(buf.InternalList, buf.InternalStart, buf.Count, outChars, outIndex, flush));
 }
Example #10
0
 void ReduceStepWithSlices(ArraySlice<double> first, ArraySlice<double> second)
 {
     var length = first.Length;
     for (var i = 0; i < length; i++)
     {
         first[i] = first[i] + second[i];
     }
 }
Example #11
0
        /// <summary>Encodes a byte array to a string with BAIS encoding, which preserves
        /// runs of ASCII characters unchanged.</summary>
        /// <param name="allowControlChars">If true, control characters under 32 are
        ///   treated as ASCII (except character 8 '\b').</param>
        /// <returns>The encoded string.</returns>
        /// <remarks>
        /// If the byte array can be interpreted as ASCII, it is returned as characters,
        /// e.g. <c>Convert(new byte[] { 65,66,67,33 }) == "ABC!"</c>. When non-ASCII
        /// bytes are encountered, they are encoded as described in the description of
        /// this class.
        /// <para/>
        /// For simplicity, this method's base-64 encoding always encodes groups of
        /// three bytes if possible (as four characters). This decision may,
        /// unfortunately, cut off the beginning of some ASCII runs.
        /// </remarks>
        public static string Convert(ArraySlice <byte> bytes, bool allowControlChars = true)
        {
            var sb = new StringBuilder();

            while (RangeExt.TryPopFirst(ref bytes, out byte b))
            {
                if (IsAscii(b, allowControlChars))
                {
                    sb.Append((char)b);
                }
                else
                {
                    sb.Append('\b');
                    // Do binary encoding in groups of 3 bytes
                    for (;; b = bytes.PopFirst(out bool _))
                    {
                        int accum = b;
                        if (RangeExt.TryPopFirst(ref bytes, out b))
                        {
                            accum = (accum << 8) | b;
                            if (RangeExt.TryPopFirst(ref bytes, out b))
                            {
                                accum = (accum << 8) | b;
                                sb.Append(EncodeBase64Digit(accum >> 18));
                                sb.Append(EncodeBase64Digit(accum >> 12));
                                sb.Append(EncodeBase64Digit(accum >> 6));
                                sb.Append(EncodeBase64Digit(accum));
                                if (bytes.IsEmpty)
                                {
                                    break;
                                }
                            }
                            else
                            {
                                sb.Append(EncodeBase64Digit(accum >> 10));
                                sb.Append(EncodeBase64Digit(accum >> 4));
                                sb.Append(EncodeBase64Digit(accum << 2));
                                break;
                            }
                        }
                        else
                        {
                            sb.Append(EncodeBase64Digit(accum >> 2));
                            sb.Append(EncodeBase64Digit(accum << 4));
                            break;
                        }
                        if (IsAscii(bytes.First, allowControlChars) &&
                            IsAscii(bytes[1, 32], allowControlChars) &&
                            IsAscii(bytes[2, 32], allowControlChars))
                        {
                            sb.Append('!');                             // return to ASCII mode
                            break;
                        }
                    }
                }
            }
            return(sb.ToString());
        }
Example #12
0
        public void ArraySliceTests_Basics()
        {
            int[]            sample       = Enumerable.Range(100, 50).ToArray();
            int[]            copyToTarget = new int[100];
            ArraySlice <int> slice;

            // Empty ArraySlice
            slice = ArraySlice <int> .Empty;
            slice.Trim();
            Assert.Empty(slice);
            Assert.True(slice == ArraySlice <int> .Empty);
            Assert.False(slice != ArraySlice <int> .Empty);

            VerifyCopyTo <int>(slice, copyToTarget);
            VerifyRoundTrip <int>(slice, copyToTarget);
            CollectionReadVerifier.VerifySame(slice, TreeSerializer.RoundTrip(slice, TreeFormat.Binary));
            CollectionReadVerifier.VerifySame(slice, TreeSerializer.RoundTrip(slice, TreeFormat.Json));

            // Whole Array
            slice = new ArraySlice <int>(sample);
            Assert.Equal(sample.Length, slice.Count);
            Assert.Equal(sample, slice);
            Assert.Equal(sample[10], slice[10]);
            VerifyCopyTo <int>(slice, copyToTarget);
            VerifyRoundTrip <int>(slice, copyToTarget);
            CollectionReadVerifier.VerifySame(slice, TreeSerializer.RoundTrip(slice, TreeFormat.Binary));
            CollectionReadVerifier.VerifySame(slice, TreeSerializer.RoundTrip(slice, TreeFormat.Json));

            // Array slice-to-end
            slice = new ArraySlice <int>(sample, index: 10);
            Assert.Equal(sample.Length - 10, slice.Count);
            Assert.Equal(sample[20], slice[10]);
            Assert.False(slice.Equals(sample));
            VerifyCopyTo <int>(slice, copyToTarget);
            VerifyRoundTrip <int>(slice, copyToTarget);
            CollectionReadVerifier.VerifySame(slice, TreeSerializer.RoundTrip(slice, TreeFormat.Binary));
            CollectionReadVerifier.VerifySame(slice, TreeSerializer.RoundTrip(slice, TreeFormat.Json));

            // Array slice
            slice = new ArraySlice <int>(sample, index: 10, length: 20);
            Assert.Equal(20, slice.Count);
            Assert.Equal(sample[10], slice[0]);
            VerifyCopyTo <int>(slice, copyToTarget);
            VerifyRoundTrip <int>(slice, copyToTarget);
            CollectionReadVerifier.VerifySame(slice, TreeSerializer.RoundTrip(slice, TreeFormat.Binary));
            CollectionReadVerifier.VerifySame(slice, TreeSerializer.RoundTrip(slice, TreeFormat.Json));

            // Bounds checks
            Assert.Throws <ArgumentNullException>(() => new ArraySlice <int>(null, 0, 0));                            // Array null
            Assert.Throws <ArgumentOutOfRangeException>(() => new ArraySlice <int>(sample, -1, 0));                   // index < 0
            Assert.Throws <ArgumentOutOfRangeException>(() => new ArraySlice <int>(sample, sample.Length + 1, 0));    // index > array.Length
            Assert.Throws <ArgumentOutOfRangeException>(() => new ArraySlice <int>(sample, 0, sample.Length + 1));    // length too long
            Assert.Throws <ArgumentOutOfRangeException>(() => new ArraySlice <int>(sample, 2, sample.Length + 3));

            // Clear
            slice.Clear();
            Assert.Empty(slice);
        }
        unsafe ArraySlice <float> inner(int val)
        {
            var mm = new UnmanagedMemoryBlock <float>(15, val);

            var addr = (IntPtr)mm.Address;
            var arr  = new ArraySlice <float>(mm);

            return(arr.Slice(5, 5));
        }
Example #14
0
    void ReduceStepWithSlices(ArraySlice <double> first, ArraySlice <double> second)
    {
        var length = first.Length;

        for (var i = 0; i < length; i++)
        {
            first[i] = first[i] + second[i];
        }
    }
        public void Copy(ArraySlice <double> x, ArraySlice <double> y)
        {
            if (x.Length != y.Length)
            {
                throw new ArgumentException(Constants.Exceptions.ArrayLengthMustBeEqual);
            }

            VclNativeMethods.vclCopy(x.Length, x.Array, x.Offset, y.Array, y.Offset);
        }
        public void Axpby(double alpha, ArraySlice <double> x, double beta, ArraySlice <double> y)
        {
            if (x.Length != y.Length)
            {
                throw new ArgumentException(Constants.Exceptions.ArrayLengthMustBeEqual);
            }

            VclNativeMethods.vclAxpby(x.Length, alpha, x.Array, x.Offset, beta, y.Array, y.Offset);
        }
        public double Dot(ArraySlice <double> x, int incx, ArraySlice <double> y, int incy)
        {
            if (incx <= 0 || incy <= 0)
            {
                throw new ArgumentException(Constants.Exceptions.IncrementsMustBePositive);
            }

            return(VclNativeMethods.vclDotEx(x.Length, x.Array, x.Offset, incx, y.Array, y.Offset, incy));
        }
        public double Dot(ArraySlice <double> x, ArraySlice <double> y)
        {
            if (x.Length != y.Length)
            {
                throw new ArgumentException(Constants.Exceptions.ArrayLengthMustBeEqual);
            }

            return(VclNativeMethods.vclDot(x.Length, x.Array, x.Offset, y.Array, y.Offset));
        }
        public void CreationButNotUsing()
        {
            int offset = 10;
            var data   = InitializeData();

            var segment = new ArraySlice <float>(data, offset, 5);

            AccessAsParameter(segment);
        }
        private double EntropyOfCond(ArraySlice<DecisionTest> S)
        {
            double p1;
            int index = Split(S, out p1);
            double p2 = 1.0 - p1;

            double result = (Functions.Entropy(p1) + Functions.Entropy(1 - p1)) / platform.BranchCost;
            return result;
        }
        public void Divide(ArraySlice <double> a, ArraySlice <double> b)
        {
            if (a.Length != b.Length)
            {
                throw new ArgumentException(Constants.Exceptions.ArrayLengthMustBeEqual);
            }

            VclNativeMethods.vclDivide(a.Length, a.Array, a.Offset, b.Array, b.Offset);
        }
Example #22
0
        /// <summary>
        ///     Return a new array of given shape and type, filled with fill_value.
        /// </summary>
        /// <param name="fill_value">Fill value.</param>
        /// <param name="shape">Shape of the empty array, e.g., (2, 3) or 2.</param>
        /// <param name="typeCode">The desired data-type for the array The default, null, means np.array(fill_value).dtype.</param>
        /// <returns>Array of fill_value with the given shape, dtype, and order.</returns>
        /// <remarks>https://docs.scipy.org/doc/numpy/reference/generated/numpy.full.html</remarks>
        public static NDArray full(ValueType fill_value, Shape shape, NPTypeCode typeCode)
        {
            if (typeCode == NPTypeCode.Empty)
            {
                throw new ArgumentNullException(nameof(typeCode));
            }

            return(new NDArray(new UnmanagedStorage(ArraySlice.Allocate(typeCode, shape.size, Convert.ChangeType(fill_value, (TypeCode)typeCode)), shape)));
        }
Example #23
0
        public override NDArray Cast(NDArray nd, NPTypeCode dtype, bool copy)
        {
            if (dtype == NPTypeCode.Empty)
            {
                throw new ArgumentNullException(nameof(dtype));
            }

            NDArray clone() => new NDArray(nd.Storage.Clone());

            if (nd.Shape.IsEmpty)
            {
                if (copy)
                {
                    return(new NDArray(dtype));
                }

                nd.Storage = new UnmanagedStorage(dtype);
                return(nd);
            }

            if (nd.Shape.IsScalar || (nd.Shape.size == 1 && nd.Shape.NDim == 1))
            {
                var ret = NDArray.Scalar(nd.GetAtIndex(0), dtype);
                if (copy)
                {
                    return(ret);
                }

                nd.Storage = ret.Storage;
                return(nd);
            }

            if (nd.GetTypeCode == dtype)
            {
                //casting not needed
                return(copy ? clone() : nd);
            }
            else
            {
                //casting needed
                if (copy)
                {
                    if (nd.Shape.IsSliced)
                    {
                        nd = clone();
                    }

                    return(new NDArray(new UnmanagedStorage(ArraySlice.FromMemoryBlock(nd.Array.CastTo(dtype), false), nd.Shape)));
                }
                else
                {
                    var storage = nd.Shape.IsSliced ? nd.Storage.Clone() : nd.Storage;
                    nd.Storage = new UnmanagedStorage(ArraySlice.FromMemoryBlock(storage.InternalArray.CastTo(dtype), false), storage.Shape);
                    return(nd);
                }
            }
        }
Example #24
0
        private static void ReduceStepWithSlices(ArraySlice <double> first, ArraySlice <double> second)
        {
            int length = first.Length;

            for (int i = 0; i < length; i++)
            {
                first[i] = first[i] + second[i];
            }
        }
 /// <summary>
 /// Sets the initial data to use when creating the <see cref="Buffer{TElement}"/>. Resources with a usage of
 /// <see cref="ResourceUsage.Immutable"/> must have initial data provided.
 /// </summary>
 /// <param name="initialData">The data to set.
 /// If not null, the resultant buffer will have a length equal to the <see cref="ArraySlice{T}.Length"/>
 /// property. This means if you previously set a length with <see cref="WithLength"/>, the value will be overwritten.
 /// If null, no initial data will be set.</param>
 /// <returns>An identical BufferBuilder with the specified <paramref name="initialData"/> parameter.</returns>
 public override BufferBuilder <TElement> WithInitialData(ArraySlice <TElement>?initialData)
 {
     return(new BufferBuilder <TElement>(
                Usage,
                initialData != null ? initialData.Value.Length : length,
                permittedBindings,
                initialData
                ));
 }
Example #26
0
        public void RowAccess()
        {
            var a = ArraySlice <int> .Range(4).Reshape(2, 2);

            var row1 = a["0"];

            Assert.AreEqual(row1[0], 0);
            Assert.AreEqual(row1[1], 1);
        }
 internal BufferBuilder(ResourceUsage usage, uint length, GPUBindings permittedBindings,
                        ArraySlice <TElement>?initialData)
     : base(usage, initialData)
 {
     Assure.True(typeof(TElement).IsBlittable());
     Assure.GreaterThan(UnsafeUtils.SizeOf <TElement>(), 0);
     this.length            = length;
     this.permittedBindings = permittedBindings;
 }
Example #28
0
        public void NestedView_2D()
        {
            var data = new ArraySlice <int>(new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }).Reshape(2, 10);
            //>>> x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
            //>>> x = x.reshape(2, 10)
            //>>> x
            //array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
            //       [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])
            // return identical view
            var identical = new ArraySlice <int>(data, ":");

            Assert.AreEqual(new Shape(2, 10), identical.Shape);
            //>>> x[:, 1:9]
            //array([[1, 2, 3, 4, 5, 6, 7, 8],
            //       [1, 2, 3, 4, 5, 6, 7, 8]])
            var view1 = new ArraySlice <int>(identical, ":,1:9");

            Assert.AreEqual(new Shape(2, 8), view1.Shape);
            Assert.AreEqual(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8 }, view1);
            //>>> x[:, 1:9][:,::- 2]
            //array([[8, 6, 4, 2],
            //       [8, 6, 4, 2]])
            var view2 = new ArraySlice <int>(view1, ":,::-2");

            Assert.AreEqual(new Shape(2, 4), view2.Shape);
            Assert.AreEqual(new int[] { 8, 6, 4, 2, 8, 6, 4, 2 }, view2);
            //>>> x[:, 1:9][:,::- 2][:,::- 3]
            //array([[2, 8],
            //       [2, 8]])
            var view3 = new ArraySlice <int>(view2, ":,::-3");

            Assert.AreEqual(new Shape(2, 2), view3.Shape);
            Assert.AreEqual(new int[] { 2, 8, 2, 8 }, view3);
            // all must see the same modifications, no matter if original or any view is modified
            // modify original
            data.SetValues(0, new int[] { 0, -1, -2, -3, -4, -5, -6, -7, -8, -9, 0, -1, -2, -3, -4, -5, -6, -7, -8, -9 });
            Assert.AreEqual(new int[] { -1, -2, -3, -4, -5, -6, -7, -8, -1, -2, -3, -4, -5, -6, -7, -8 }, view1);
            Assert.AreEqual(new int[] { -8, -6, -4, -2, -8, -6, -4, -2 }, view2);
            Assert.AreEqual(new int[] { -2, -8, -2, -8 }, view3);
            // modify views
            view1[0, 7] = 88;
            view1[1, 7] = 888;
            Assert.AreEqual(new int[] { 0, -1, -2, -3, -4, -5, -6, -7, 88, -9, 0, -1, -2, -3, -4, -5, -6, -7, 888, -9 },
                            data);
            Assert.AreEqual(new int[] { -1, -2, -3, -4, -5, -6, -7, 88, -1, -2, -3, -4, -5, -6, -7, 888 },
                            view1);
            Assert.AreEqual(new int[] { 88, -6, -4, -2, 888, -6, -4, -2 }, view2);
            Assert.AreEqual(new int[] { -2, 88, -2, 888 }, view3);
            view3[0, 0] = 22;
            view3[1, 0] = 222;
            Assert.AreEqual(new int[] { 0, -1, 22, -3, -4, -5, -6, -7, 88, -9, 0, -1, 222, -3, -4, -5, -6, -7, 888, -9 },
                            data);
            Assert.AreEqual(new int[] { -1, 22, -3, -4, -5, -6, -7, 88, -1, 222, -3, -4, -5, -6, -7, 888 },
                            view1);
            Assert.AreEqual(new int[] { 88, -6, -4, 22, 888, -6, -4, 222 }, view2);
            Assert.AreEqual(new int[] { 22, 88, 222, 888 }, view3);
        }
        public float[] DoNotOptimizeAccessSetter()
        {
            int offset = 10;
            var data = InitializeData();

            var segment = new ArraySlice<float>(data, offset, 5);
            segment[4] = 999;

            return segment.Array;
        }
Example #30
0
 public static void Copy <T>(T[] source, int sourceOffset, ArraySlice <T> destination, int destinationOffset, int length)
 {
     Array.Copy(
         source,
         sourceOffset,
         destination.Pointer,
         destination.Offset + destinationOffset,
         length
         );
 }
Example #31
0
 public static void Copy <T>(ArraySlice <T> source, int sourceOffset, T[] destination, int destinationOffset, int length)
 {
     Array.Copy(
         source.Pointer,
         source.Offset + sourceOffset,
         destination,
         destinationOffset,
         length
         );
 }
Example #32
0
 public ThrowCommand(ArraySlice <byte> data)
     : base(data, "Throw", 0xC)
 {
     Damage          = data.GetInt16(2) >> 0 & 0x1FF;
     KnockbackGrowth = data.GetInt16(5) >> 6 & 0x1FF;
     Element         = (ElementType)(data.GetInt16(9) >> 3 & 0xF);
     Angle           = data.GetInt16(4) >> 7 & 0x1FF;
     BaseKnockback   = data.GetInt16(8) >> 7 & 0x1FF;
     ThrowType       = (ThrowTypes)(data.GetInt16(0) >> 7 & 0x7);
 }
Example #33
0
        public void AddValues(ArraySlice <byte> values, BitVector vector)
        {
            byte[] array = values.Array;
            int    end   = values.Index + values.Count;

            for (int i = values.Index; i < end; ++i)
            {
                vector[array[i]] = true;
            }
        }
        public float DoNotOptimizeAccessGetter()
        {
            int offset = 10;
            var data = InitializeData();

            var segment = new ArraySlice<float>(data, offset, 5);
            float result = segment[4];

            return result;
        }
Example #35
0
        /// <summary>
        /// Constructor which takes .NET array
        /// dtype and shape is determined from array
        /// </summary>
        /// <param name="values"></param>
        /// <param name="shape"></param>
        /// <param name="order"></param>
        /// <returns>Array with values</returns>
        /// <remarks>This constructor calls <see cref="IStorage.Allocate(NumSharp.Shape,System.Type)"/></remarks>
        public NDArray(Array values, Shape shape = default, char order = 'C') : this(values.GetType().GetElementType())
        {
            if (order != 'C')
                shape.ChangeTensorLayout(order);

            if (shape.IsEmpty)
                shape = Shape.ExtractShape(values);

            Storage.Allocate(values.ResolveRank() != 1 ? ArraySlice.FromArray(Arrays.Flatten(values), false) : ArraySlice.FromArray(values, false), shape);
        }
        public T[] GenericGetter <T>()
        {
            int offset = 10;
            var data   = InitializeData <T>();

            var segment = new ArraySlice <T>(data, offset, 5);
            T   result  = segment[4];

            return(segment.Array);
        }
        public float SingleAccessGetter()
        {
            int offset = 10;
            var data   = InitializeData();

            var   segment = new ArraySlice <float>(data, offset, 5);
            float result  = segment[4];

            return(result);
        }
        public void ViennaHostProvider_Add()
        {
            var provider = new VclHostTensorMath();

            var x = new ArraySlice<double>(10);
            provider.Set(10.0d, x);
            provider.Add(10.0d, x);

            Assert.All(x, xx => MathHelpers.Equality(xx, 20.0d));
        }
        void IBuffer.DiscardWrite(ArraySlice <byte> data, uint offset)
        {
            GCHandle pinnedDataHandle = GCHandle.Alloc(data.ContainingArray, GCHandleType.Pinned);

            try {
                MapDiscardWrite(pinnedDataHandle.AddrOfPinnedObject() + (int)data.Offset, data.Length, offset);
            }
            finally {
                pinnedDataHandle.Free();
            }
        }
        public void ViennaHostProvider_Add()
        {
            var provider = new VclHostTensorMath();

            var x = new ArraySlice <double>(10);

            provider.Set(10.0d, x);
            provider.Add(10.0d, x);

            Assert.All(x, xx => MathHelpers.Equality(xx, 20.0d));
        }
        private double EntropyOfSwitch(ArraySlice<DecisionTest> S)
        {
            double result = 0;

            foreach (var test in S)
            {
                result += Functions.Entropy(test.Probability);
            }

            result /= platform.SwitchCost;
            return result;
        }
Example #42
0
        void ICpuTensorMath.Abs(ArraySlice<double> a, ArraySlice<double> b)
        {
            Contract.Requires(a != null);
            Contract.Requires(b != null);
            Contract.Requires(a.Length == b.Length);

            Contract.Requires(Contract.ForAll(a, xx => !double.IsNaN(xx)));
            Contract.Requires(Contract.ForAll(b, yy => !double.IsNaN(yy)));

            Contract.Ensures(Contract.ForAll(b, xx => xx >= 0));
            Contract.Ensures(Contract.ForAll(b, bb => !double.IsNaN(bb)));
        }
Example #43
0
    double ReduceRecursiveWithSlices(ArraySlice<double> array)
    {
        var watch = new Stopwatch();
        watch.Start();

        var size = array.Length/2;
        ReduceRecursiveStepWithSlices(new ArraySlice<double>(array, 0, size), new ArraySlice<double>(array, size, size));

        watch.Stop();

        Console.WriteLine(string.Format("Reduced with ArraySlice-Recursive: '{0}' elements in {1}ms.", array.Length, watch.ElapsedMilliseconds));
        return array[0];
    }
        public void ViennaHostProvider_Abs()
        {
            var provider = new VclHostTensorMath();

            var x = new ArraySlice<double>(10);
            for (int i = 0; i < x.Length; i++)
                x[i] = -i;

            var y = new ArraySlice<double>(10);
            provider.Abs(x, y);

            for (int i = 0; i < x.Length; i++)
                Assert.True(MathHelpers.Equality(Math.Abs(x[i]), y[i]));
        }
        public void ViennaHostProvider_AbsSum()
        {
            var provider = new VclHostTensorMath();

            var x = new ArraySlice<double>(10);
            for (int i = 0; i < x.Length; i++)
                x[i] = -i;

            var y = new ArraySlice<double>(10);
            double asum = provider.Asum(x);

            double cpu = 0;
            for (int i = 0; i < x.Length; i++)
                cpu += Math.Abs(x[i]);

            Assert.True(MathHelpers.Equality(cpu, asum));
        }
Example #46
0
    void ReduceRecursiveStepWithSlices(ArraySlice<double> first, ArraySlice<double> second)
    {
        var length = first.Length;
        if (length > 1)
        {
            for (var i = 0; i < length; i++)
            {
                first[i] = first[i] + second[i];
            }

            var size = length/2;
            ReduceRecursiveStepWithSlices(new ArraySlice<double>(first, 0, size), new ArraySlice<double>(first, size, size));
        }
        else
        {
            first[0] = first[0] + second[0];
        }
    }
Example #47
0
    double ReduceWithSlices(ArraySlice<double> array)
    {
        var watch = new Stopwatch();
        watch.Start();

        var length = array.Length;
        do
        {
            var size = length/2;
            ReduceStepWithSlices(new ArraySlice<double>(array.Array, 0, size), new ArraySlice<double>(array.Array, size, size));
            length /= 2;
        } while (length > 1);

        watch.Stop();
        Console.WriteLine($"Reduced with ArraySlice: '{array.Length}' elements in {watch.ElapsedMilliseconds}ms.");

        return array[0];
    }
Example #48
0
        public static double WithSlicesNoOptimization(ArraySlice<double> array)
        {
            Stopwatch watch = new Stopwatch();
            watch.Start();

            int lenght = array.Length;
            do
            {
                var size = lenght / 2;
                ReduceStepWithSlicesNoOptimization(new ArraySlice<double>(array.Array, 0, size), new ArraySlice<double>(array.Array, size, size));
                lenght /= 2;
            }
            while (lenght > 1);

            watch.Stop();
            Console.WriteLine(string.Format("Reduced with unoptimized ArraySlice: '{0}' elements in {1}ms.", array.Length, watch.ElapsedMilliseconds));

            return array[0];
        }
        internal JumpTableDecision(ArraySlice<DecisionTest> tests, Func<int,ActionDecision> idToAction)
        {
            this.tests = tests;
            this.startElement = tests.Array[tests.Offset].Interval.First;
            int elementCount = tests.Array[tests.Offset + tests.Count - 1].Interval.Last - startElement + 1;
            this.elementToAction = new Decision[elementCount];

            foreach (var test in tests)
            {
                var action = idToAction(test.Action);
                if (!leafDecisions.Contains(action))
                {
                    leafDecisions.Add(action);
                }

                for (int i = test.Interval.First; i <= test.Interval.Last; ++i)
                {
                    elementToAction[i - startElement] = action;
                }
            }
        }
        public void ViennaHostProvider_AbsSumWithRollingArray()
        {
            var provider = new VclHostTensorMath();

            var x = new double[20];
            for (int i = 0; i < x.Length; i++)
                x[i] = -i;

            var results = new double[10];
            for (int i = 0; i < results.Length; i++)
            {
                var y = new ArraySlice<double> (x, i, results.Length);
                results[i] = provider.Asum(x);
            }

            double cpu = 0;
            for (int i = 0; i < 10; i++)
                cpu += Math.Abs(x[i]);

            Assert.All(results, r => MathHelpers.Equality(r, cpu));
        }
Example #51
0
        static void Ifct8(ArraySlice<float> bloque, ArraySlice<float> res, float[,] tIcos)
        {
            float dc = bloque[0] * tIcos[0, 0];

            float suma02 = 0;
            suma02 += bloque[4] * tIcos[4, 0];

            float suma01 = 0;
            suma01 += bloque[2] * tIcos[2, 0];
            suma01 += bloque[6] * tIcos[6, 0];

            float suma11 = 0;
            suma11 += bloque[2] * tIcos[2, 1];
            suma11 += bloque[6] * tIcos[6, 1];

            float suma00 = 0;
            suma00 += bloque[1] * tIcos[1, 0];
            suma00 += bloque[3] * tIcos[3, 0];
            suma00 += bloque[5] * tIcos[5, 0];
            suma00 += bloque[7] * tIcos[7, 0];

            float suma10 = 0;
            suma10 += bloque[1] * tIcos[1, 1];
            suma10 += bloque[3] * tIcos[3, 1];
            suma10 += bloque[5] * tIcos[5, 1];
            suma10 += bloque[7] * tIcos[7, 1];

            float suma20 = 0;
            suma20 += bloque[1] * tIcos[1, 2];
            suma20 += bloque[3] * tIcos[3, 2];
            suma20 += bloque[5] * tIcos[5, 2];
            suma20 += bloque[7] * tIcos[7, 2];

            float suma30 = 0;
            suma30 += bloque[1] * tIcos[1, 3];
            suma30 += bloque[3] * tIcos[3, 3];
            suma30 += bloque[5] * tIcos[5, 3];
            suma30 += bloque[7] * tIcos[7, 3];

            float p00 = dc + suma02;
            float p01 = dc - suma02;

            float p10 = p00 + suma01;
            float p11 = p00 - suma01;
            float p12 = p01 + suma11;
            float p13 = p01 - suma11;

            res[0] = p10 + suma00;
            res[7] = p10 - suma00;
            res[3] = p11 + suma30;
            res[4] = p11 - suma30;
            res[1] = p12 + suma10;
            res[6] = p12 - suma10;
            res[2] = p13 + suma20;
            res[5] = p13 - suma20;
        }
        public void ViennaHostProvider_Dot()
        {
            var provider = new VclHostTensorMath();

            var x = new ArraySlice<double>(10);
            var y = new ArraySlice<double>(10);
            for (int i = 0; i < x.Length; i++)
            {
                x[i] = i;
                y[i] = i;
            }

            double result = provider.Dot(x, y);
            double resultEx = provider.Dot(x, 1, y, 1);

            double cpu = 0;
            for (int i = 0; i < x.Length; i++)
                cpu += x[i] * y[i];

            Assert.True(MathHelpers.Equality(cpu, result));
            Assert.True(MathHelpers.Equality(cpu, resultEx));
        }
        public void ViennaHostProvider_Gemm_SquareWithAdd()
        {
            var provider = new VclHostTensorMath();

            int size = 4;

            var x = new ArraySlice<double>(size * size);
            var y = new ArraySlice<double>(size * size);
            for (int i = 0; i < x.Length; i++)
            {
                int ii = i % size;
                int jj = i / size;

                x[i] = i;
                if (ii == jj)
                    y[i] = 1;
            }

            var r = new ArraySlice<double>(size * size);
            provider.Set(2, r);
            provider.Gemm(BlasTranspose.None, BlasTranspose.None, size, size, size, 1.0d, x, y, 1.0d, r);

            for (int i = 0; i < x.Length; i++)
                Assert.True(MathHelpers.Equality(x[i] + 2, r[i]));
        }
        public void ViennaHostProvider_Powx()
        {
            var provider = new VclHostTensorMath();

            var x = new ArraySlice<double>(10);
            var y = new ArraySlice<double>(10);
            for (int i = 0; i < x.Length; i++)
            {
                x[i] = i;
                y[i] = 2;
            }

            provider.Powx(x, y);
            provider.Powx(x, x);

            for (int i = 0; i < x.Length; i++)
            {
                Assert.True(MathHelpers.Equality(Math.Pow(i, i), x[i]));
                Assert.True(MathHelpers.Equality(Math.Pow(i, 2), y[i]));
            }
        }
        public void ViennaHostProvider_Axpby()
        {
            var provider = new VclHostTensorMath();

            var x = new ArraySlice<double>(10);
            provider.Set(10.0d, x);

            var y = new ArraySlice<double>(10);
            provider.Set(5.0d, y);

            provider.Axpby(1, x, 2, y);

            var z = new ArraySlice<double>(10);
            provider.Set(10.0d, z);

            provider.Axpy(2, x, z);

            Assert.All(y, yy => MathHelpers.Equality(yy, 20.0d));
            Assert.All(z, zz => MathHelpers.Equality(zz, 30.0d));
        }
        public void ViennaHostProvider_Scale()
        {
            var provider = new VclHostTensorMath();

            var x = new ArraySlice<double>(10);
            for (int i = 0; i < x.Length; i++)
                x[i] = i;

            var y = new ArraySlice<double>(10);
            provider.Scale(2, x, y);
            provider.Scale(2, x);

            for (int i = 0; i < x.Length; i++)
            {
                Assert.True(MathHelpers.Equality(2 * i, y[i]));
                Assert.True(MathHelpers.Equality(x[i], y[i]));
            }
        }
        public void ViennaHostProvider_Substract()
        {
            var provider = new VclHostTensorMath();

            var x = new ArraySlice<double>(10);
            provider.Set(10.0d, x);

            var y = new ArraySlice<double>(10);
            provider.Set(5.0d, y);

            provider.Substract(x, y);

            Assert.All(y, yy => MathHelpers.Equality(yy, 5.0d));
        }
Example #58
0
        void ICpuTensorMath.Add(double alpha, ArraySlice<double> y)
        {
            Contract.Requires(y != null);

            Contract.Requires(Contract.ForAll(y, yy => !double.IsNaN(yy)));
            Contract.Ensures(Contract.ForAll(y, yy => !double.IsNaN(yy)));
        }
        public void ViennaHostProvider_Square()
        {
            var provider = new VclHostTensorMath();

            var x = new ArraySlice<double>(10);
            var y = new ArraySlice<double>(10);
            for (int i = 0; i < x.Length; i++)
            {
                x[i] = i;
                y[i] = 2;
            }

            provider.Square(x, y);

            for (int i = 0; i < x.Length; i++)
                Assert.True(MathHelpers.Equality(x[i] * x[i], y[i]));
        }
        public void ViennaHostProvider_Set()
        {
            var provider = new VclHostTensorMath();

            var y = new ArraySlice<double>(10);
            provider.Set(10.0d, y);

            var yInt = new ArraySlice<double>(10);
            provider.Set(10, yInt);

            Assert.All(y, yy => MathHelpers.Equality(yy, 10.0d));
            Assert.All(yInt, yyInt => MathHelpers.Equality(yyInt, 10.0d));
        }