Пример #1
0
        public void Case11_Scalar()
        {
            var sh = new ValueCoordinatesIncrementor(new int[0]);

            sh.Index.Should().ContainInOrder(0);
            sh.Next().Should().BeNull();
        }
Пример #2
0
        public void Case1()
        {
            var shape = new Shape(3, 3, 1, 2);
            var sh    = new ValueCoordinatesIncrementor(ref shape); //ValueCoordinatesIncrementor

            sh.Index.Should().ContainInOrder(0, 0, 0, 0);
            sh.Next().Should().ContainInOrder(0, 0, 0, 1);
            sh.Next().Should().ContainInOrder(0, 1, 0, 0);
            sh.Next().Should().ContainInOrder(0, 1, 0, 1);
            sh.Next().Should().ContainInOrder(0, 2, 0, 0);
            sh.Next().Should().ContainInOrder(0, 2, 0, 1);
            sh.Next().Should().ContainInOrder(1, 0, 0, 0);
            sh.Next().Should().ContainInOrder(1, 0, 0, 1);
            sh.Next().Should().ContainInOrder(1, 1, 0, 0);
            sh.Next().Should().ContainInOrder(1, 1, 0, 1);
            sh.Next().Should().ContainInOrder(1, 2, 0, 0);
            sh.Next().Should().ContainInOrder(1, 2, 0, 1);
            sh.Next().Should().ContainInOrder(2, 0, 0, 0);
            sh.Next().Should().ContainInOrder(2, 0, 0, 1);
            sh.Next().Should().ContainInOrder(2, 1, 0, 0);
            sh.Next().Should().ContainInOrder(2, 1, 0, 1);
            sh.Next().Should().ContainInOrder(2, 2, 0, 0);
            sh.Next().Should().ContainInOrder(2, 2, 0, 1);
            sh.Next().Should().BeNull();
        }
Пример #3
0
        public void Case10_Scalar_2()
        {
            var shape = Shape.Scalar;
            var sh    = new ValueCoordinatesIncrementor(ref shape);

            sh.Index.Should().ContainInOrder(0);
            sh.Next().Should().BeNull();
        }
Пример #4
0
        public void Case6()
        {
            var shape = new Shape(1);
            var sh    = new ValueCoordinatesIncrementor(ref shape);

            sh.Index.Should().ContainInOrder(0);

            sh.Next().Should().BeNull();
        }
        public override NDArray ReduceArgMax(NDArray arr, int? axis_)
        {
            //in order to iterate an axis:
            //consider arange shaped (1,2,3,4) when we want to summarize axis 1 (2nd dimension which its value is 2)
            //the size of the array is [1, 2, n, m] all shapes after 2nd multiplied gives size
            //the size of what we need to reduce is the size of the shape of the given axis (shape[axis])
            var shape = arr.Shape;
            if (shape.IsEmpty)
                return arr;

            if (shape.IsScalar || (shape.size == 1 && shape.NDim == 1))
                return NDArray.Scalar(0);

            if (axis_ == null)
                return NDArray.Scalar(argmax_elementwise(arr));

            var axis = axis_.Value;
            while (axis < 0)
                axis = arr.ndim + axis; //handle negative axis

            if (axis >= arr.ndim)
                throw new ArgumentOutOfRangeException(nameof(axis));

            if (shape[axis] == 1)
            {
                //if the given div axis is 1 and can be squeezed out.
                return np.squeeze_fast(arr, axis);
            }

            //handle keepdims
            Shape axisedShape = Shape.GetAxis(shape, axis);

            //prepare ret
            var ret = new NDArray(NPTypeCode.Int32, axisedShape, false);
            var iterAxis = new NDCoordinatesAxisIncrementor(ref shape, axis);
            var iterRet = new ValueCoordinatesIncrementor(ref axisedShape);
            var iterIndex = iterRet.Index;
            var slices = iterAxis.Slices;

#if _REGEN
            #region Compute
            switch (arr.GetTypeCode)
		    {
			    %foreach supported_numericals,supported_numericals_lowercase%
			    case NPTypeCode.#1: 
                {
                    int at;
                    do
                    {
                        var iter = arr[slices].AsIterator<#2>();
Пример #6
0
        /// <summary>
        ///     Random values in a given shape.
        ///     Create an array of the given shape and populate it with random samples from a uniform distribution over [0, 1).
        /// </summary>
        public NDArray rand(Shape shape)
        {
            NDArray ret = new NDArray(typeof(double), shape, false);

            unsafe
            {
                var addr = (double *)ret.Address;
                var incr = new ValueCoordinatesIncrementor(ref shape);
                do
                {
                    *(addr + shape.GetOffset(incr.Index)) = randomizer.NextDouble();
                } while (incr.Next() != null);
            }

            return(ret);
        }
Пример #7
0
        /// <remarks>https://docs.scipy.org/doc/numpy/reference/generated/numpy.matmul.html</remarks>
        public override NDArray Matmul(NDArray lhs, NDArray rhs)
        {
            if (lhs.Shape.IsScalar || rhs.Shape.IsScalar)
            {
                throw new InvalidOperationException("Matmul can't handle scalar multiplication, use `*` or `np.dot(..)` instead");
            }

            //If the first argument is 1-D, it is promoted to a matrix by prepending a 1 to its dimensions. After matrix multiplication the prepended 1 is removed.
            if (lhs.ndim == 1 && rhs.ndim == 2)
            {
                throw new NotSupportedException("Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?)");
            }

            if (rhs.ndim == 1)
            {
                rhs = np.expand_dims(rhs, 1);
            }

            if (lhs.ndim == 2 || rhs.ndim == 2)
            {
                return(MultiplyMatrix(lhs, rhs));
            }

            NDArray l = lhs;
            NDArray r = rhs;

            (l, r) = np.broadcast_arrays(l, r);
            var retShape = l.Shape.Clean();

            Console.WriteLine(retShape);
            Debug.Assert(l.shape[0] == r.shape[0]);
            var len       = l.size;
            var ret       = new NDArray(np._FindCommonArrayType(l.typecode, r.typecode), retShape);
            var iterShape = new Shape(retShape.dimensions.Take(retShape.dimensions.Length - 2).ToArray());
            var incr      = new ValueCoordinatesIncrementor(ref iterShape);
            var index     = incr.Index;

            for (int i = 0; i < len; i++, incr.Next())
            {
                MultiplyMatrix(l[index], r[index], ret[index]);
            }

            return(ret);
        }
Пример #8
0
        public Array ToMuliDimArray <T>() where T : unmanaged
        {
            var ret = Arrays.Create(typeof(T), shape);

            var iter      = this.AsIterator <T>();
            var hasNext   = iter.HasNext;
            var next      = iter.MoveNext;
            var coorditer = new ValueCoordinatesIncrementor(shape);
            var indices   = coorditer.Index;

            while (hasNext())
            {
                ret.SetValue(next(), indices);
                if (coorditer.Next() == null)
                {
                    break;
                }
            }

            return(ret);
        }
Пример #9
0
        /// <summary>
        /// Test whether all array elements evaluate to True.
        /// </summary>
        /// <param name="nd"></param>
        /// <returns></returns>
        public override bool All(NDArray nd)
        {
            if (nd.GetTypeCode != NPTypeCode.Boolean)
            {
                throw new NotSupportedException("DefaultEngine.All supports only boolean dtype."); //TODO!
            }
            unsafe
            {
                var addr  = (bool *)nd.Address;
                var shape = nd.Shape;
                var incr  = new ValueCoordinatesIncrementor(shape.dimensions);
                do
                {
                    if (!(*(addr + shape.GetOffset(incr.Index))))
                    {
                        return(false);
                    }
                } while (incr.Next() != null);

                return(true);
            }
        }
Пример #10
0
        protected void autoresetDefault_Int64()
        {
            if (typeof(TOut) == typeof(Int64))
            {
                autoresetDefault_NoCast();
                return;
            }

            var   localBlock = Block;
            Shape shape      = Shape;
            var   convert    = Converts.FindConverter <Int64, TOut>();

            if (!Shape.IsContiguous || Shape.ModifiedStrides)
            {
                //Shape is sliced, auto-resetting
                switch (Type)
                {
                case IteratorType.Scalar:
                {
                    var offset = shape.TransformOffset(0);
                    if (offset != 0)
                    {
                        MoveNext          = () => convert(*((Int64 *)localBlock.Address + offset));
                        MoveNextReference = () => throw new NotSupportedException("Unable to return references during iteration when casting is involved.");
                    }
                    else
                    {
                        MoveNext          = () => convert(*((Int64 *)localBlock.Address));
                        MoveNextReference = () => throw new NotSupportedException("Unable to return references during iteration when casting is involved.");
                    }

                    Reset   = () => { };
                    HasNext = () => true;
                    break;
                }

                case IteratorType.Vector:
                {
                    var size = Shape.size;
                    MoveNext = () =>
                    {
                        var ret = convert(*((Int64 *)localBlock.Address + shape.GetOffset(index++)));
                        if (index >= size)
                        {
                            index = 0;
                        }
                        return(ret);
                    };
                    MoveNextReference = () => throw new NotSupportedException("Unable to return references during iteration when casting is involved.");

                    Reset   = () => index = 0;
                    HasNext = () => true;
                    break;
                }

                case IteratorType.Matrix:
                case IteratorType.Tensor:
                {
                    var iterator = new ValueCoordinatesIncrementor(ref shape, delegate(ref ValueCoordinatesIncrementor incr) { incr.Reset(); });
                    var index = iterator.Index;
                    Func <int[], int> getOffset = shape.GetOffset;
                    MoveNext = () =>
                    {
                        var ret = convert(*((Int64 *)localBlock.Address + getOffset(index)));
                        iterator.Next();
                        return(ret);
                    };
                    MoveNextReference = () => throw new NotSupportedException("Unable to return references during iteration when casting is involved.");
                    Reset             = () => iterator.Reset();
                    HasNext           = () => true;
                    break;
                }

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }
            else
            {
                //Shape is not sliced, auto-resetting
                switch (Type)
                {
                case IteratorType.Scalar:
                    MoveNext          = () => convert(*(Int64 *)localBlock.Address);
                    MoveNextReference = () => throw new NotSupportedException("Unable to return references during iteration when casting is involved.");
                    Reset             = () => { };
                    HasNext           = () => true;
                    break;

                case IteratorType.Vector:
                    var size = Shape.size;
                    MoveNext = () =>
                    {
                        var ret = convert(*((Int64 *)localBlock.Address + index++));
                        if (index >= size)
                        {
                            index = 0;
                        }
                        return(ret);
                    };
                    MoveNextReference = () => throw new NotSupportedException("Unable to return references during iteration when casting is involved.");
                    Reset             = () => index = 0;
                    HasNext           = () => true;
                    break;

                case IteratorType.Matrix:
                case IteratorType.Tensor:
                    var iterator = new ValueOffsetIncrementorAutoresetting(Shape);     //we do not copy the dimensions because there is not risk for the iterator's shape to change.
                    MoveNext          = () => convert(*((Int64 *)localBlock.Address + iterator.Next()));
                    MoveNextReference = () => throw new NotSupportedException("Unable to return references during iteration when casting is involved.");
                    HasNext           = () => true;
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }
        }
Пример #11
0
        protected void setDefaults_Byte() //Byte is the input type
        {
            if (AutoReset)
            {
                autoresetDefault_Byte();
                return;
            }

            if (typeof(TOut) == typeof(Byte))
            {
                setDefaults_NoCast();
                return;
            }

            var convert = Converts.FindConverter <Byte, TOut>();

            //non auto-resetting.
            var   localBlock = Block;
            Shape shape      = Shape;

            if (!Shape.IsContiguous || Shape.ModifiedStrides)
            {
                //Shape is sliced, not auto-resetting
                switch (Type)
                {
                case IteratorType.Scalar:
                {
                    var hasNext = new Reference <bool>(true);
                    var offset  = shape.TransformOffset(0);

                    if (offset != 0)
                    {
                        MoveNext = () =>
                        {
                            hasNext.Value = false;
                            return(convert(*((Byte *)localBlock.Address + offset)));
                        };
                        MoveNextReference = () => throw new NotSupportedException("Unable to return references during iteration when casting is involved.");
                    }
                    else
                    {
                        MoveNext = () =>
                        {
                            hasNext.Value = false;
                            return(convert(*((Byte *)localBlock.Address)));
                        };
                        MoveNextReference = () => throw new NotSupportedException("Unable to return references during iteration when casting is involved.");
                    }

                    Reset   = () => hasNext.Value = true;
                    HasNext = () => hasNext.Value;
                    break;
                }

                case IteratorType.Vector:
                {
                    MoveNext          = () => convert(*((Byte *)localBlock.Address + shape.GetOffset(index++)));
                    MoveNextReference = () => throw new NotSupportedException("Unable to return references during iteration when casting is involved.");
                    Reset             = () => index = 0;
                    HasNext           = () => index < Shape.size;
                    break;
                }

                case IteratorType.Matrix:
                case IteratorType.Tensor:
                {
                    var hasNext = new Reference <bool>(true);
                    var iterator = new ValueCoordinatesIncrementor(ref shape, delegate(ref ValueCoordinatesIncrementor _) { hasNext.Value = false; });
                    Func <int[], int> getOffset = shape.GetOffset;
                    var index = iterator.Index;

                    MoveNext = () =>
                    {
                        var ret = convert(*((Byte *)localBlock.Address + getOffset(index)));
                        iterator.Next();
                        return(ret);
                    };
                    MoveNextReference = () => throw new NotSupportedException("Unable to return references during iteration when casting is involved.");

                    Reset = () =>
                    {
                        iterator.Reset();
                        hasNext.Value = true;
                    };

                    HasNext = () => hasNext.Value;
                    break;
                }

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }
            else
            {
                //Shape is not sliced, not auto-resetting
                switch (Type)
                {
                case IteratorType.Scalar:
                    var hasNext = new Reference <bool>(true);
                    MoveNext = () =>
                    {
                        hasNext.Value = false;
                        return(convert(*((Byte *)localBlock.Address)));
                    };
                    MoveNextReference = () => throw new NotSupportedException("Unable to return references during iteration when casting is involved.");
                    Reset             = () => hasNext.Value = true;
                    HasNext           = () => hasNext.Value;
                    break;

                case IteratorType.Vector:
                    MoveNext          = () => convert(*((Byte *)localBlock.Address + index++));
                    MoveNextReference = () => throw new NotSupportedException("Unable to return references during iteration when casting is involved.");
                    Reset             = () => index = 0;
                    HasNext           = () => index < Shape.size;
                    break;

                case IteratorType.Matrix:
                case IteratorType.Tensor:
                    var iterator = new ValueOffsetIncrementor(Shape);     //we do not copy the dimensions because there is not risk for the iterator's shape to change.
                    MoveNext          = () => convert(*((Byte *)localBlock.Address + iterator.Next()));
                    MoveNextReference = () => throw new NotSupportedException("Unable to return references during iteration when casting is involved.");
                    Reset             = () => iterator.Reset();
                    HasNext           = () => iterator.HasNext;
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }
        }